Fred Tingaud 0bbdb53a0c
Modify Rule S2692: LaYC indexOf
Co-authored-by: Amélie Renard <44666826+amelie-renard-sonarsource@users.noreply.github.com>
2023-06-16 09:50:40 +02:00

32 lines
840 B
Plaintext

== Why is this an issue?
Most checks against an `indexOf` value compare it with -1 because 0 is a valid index. Checking against `> 0` ignores the first element, which is likely a bug.
[source,javascript]
----
var arr = ["blue", "red"];
if (arr.indexOf("blue") > 0) { // Noncompliant
// ...
}
----
Moreover, if the intent is merely to check the presence of the element, and if your browser version supports it, consider using `includes` instead.
[source,javascript]
----
var arr = ["blue", "red"];
if (arr.includes("blue")) {
// ...
}
----
This rule raises an issue when an `indexOf` value retrieved from an array is tested against `> 0`.
== Resources
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes[Array.prototype.includes()] documentation at MDN
include::../rspecator.adoc[]