73 lines
2.8 KiB
Plaintext

== Why is this an issue?
In JavaScript, there are two types of comparison operators: strict and non-strict.
* Strict operators: These operators compare both value and type. They are represented as `===` (strict equality) and `!==` (strict inequality). For example, `5 === "5"` would return `false` because, although the values are the same, the types are different (one is a number, the other is a string).
* Non-Strict operators: These operators compare only value, not type. They are represented as `==` (equality) and `!=` (inequality). For example, `5 == "5"` would return `true` because the values are the same, even though the types are different.
It's generally recommended to use strict operators in JavaScript to avoid unexpected results due to JavaScript's type coercion. This is because non-strict operators can lead to some counter-intuitive results. For example, `0 == false` would return `true`, which might not be the expected outcome.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
function checkEqual(a, b) {
if (a == b) { // Noncompliant: using non-strict equality '=='
return "Equal";
} else {
return "Not equal";
}
}
console.log(checkEqual(0, false)); // Output: "Equal"
----
You should use the strict equality and inequality operators to prevent type coercion, avoid unexpected outcomes when comparing values of different types, and provide more predictable results.
[source,javascript,diff-id=1,diff-type=compliant]
----
function checkEqual(a, b) {
if (a === b) {
return "Equal";
} else {
return "Not equal";
}
}
console.log(checkEqual(0, false)); // Output: "Not equal
----
=== Exceptions
The rule does not report on these cases:
* Comparing two literal values
* Evaluating the value of `typeof`
* Comparing against `null`
== Resources
=== Documentation
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality[Strict equality]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality[Strict inequality]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality[Equality]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality[Inequality]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion[Type coercion]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Glossary/Truthy[Truthy]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Glossary/Falsy[Falsy]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]