org.sonar.l10n.javascript.rules.javascript.S3403.html Maven / Gradle / Ivy
This rule raises an issue when a strict equality operator is used to compare objects of different types.
Why is this an issue?
The strict equality operator in JavaScript is represented by three equal signs (===
), the strict inequality with (!==
).
It is used to compare two values for equality, but with an important difference from the regular equality operator (==
). The strict
equality operator compares both value and type, while the regular equality operator only compares values after performing type coercion if
necessary.
The problem with using the strict equality operator (===
) with operands of dissimilar types lies in the way JavaScript handles the
comparison. When you use ===
to compare two values of different types, it will always return false since their types are different,
regardless of whether the values could be considered equal under certain conditions.
Code examples
Noncompliant code example
let a = 8;
let b = "8";
if (a === b) { // Noncompliant: Always false since 'a' is a number and 'b' a string
// ...
}
Compliant solution
To address this issue, you can use the loose equality operator (==
), which performs type coercion.
let a = 8;
let b = "8";
if (a == b) {
// ...
}
Alternatively, use the strict equality operator (===
) but ensure that the operands have the same type before performing the
comparison. You can explicitly convert the operands to a common type using functions like Number()
, String()
, or other
appropriate methods depending on the situation.
let a = 8;
let b = "8";
if (a === Number(b)) {
// ...
}
Resources
Documentation
- MDN - Strict equality
(
===
)
- MDN - Strict inequality
(
!==
)
- MDN - Equality (
==
)
- MDN - Inequality (
!=
)
- MDN - Type coercion
- MDN -
Number()
constructor
- MDN -
String()
constructor
- MDN -
Boolean()
constructor