2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-06-16 09:50:40 +02:00
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.
2020-06-30 12:48:07 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2020-06-30 12:48:07 +02:00
----
2023-06-16 09:50:40 +02:00
var arr = ["blue", "red"];
2020-06-30 12:48:07 +02:00
if (arr.indexOf("blue") > 0) { // Noncompliant
// ...
}
----
2023-06-16 09:50:40 +02:00
Moreover, if the intent is merely to check the presence of the element, and if your browser version supports it, consider using `includes` instead.
2020-06-30 12:48:07 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2020-06-30 12:48:07 +02:00
----
2023-06-16 09:50:40 +02:00
var arr = ["blue", "red"];
2020-06-30 12:48:07 +02:00
2021-04-26 17:29:13 +02:00
if (arr.includes("blue")) {
2020-06-30 12:48:07 +02:00
// ...
}
----
2023-06-16 09:50:40 +02:00
This rule raises an issue when an `indexOf` value retrieved from an array is tested against `> 0`.
2023-05-03 11:06:20 +02:00
== Resources
2020-06-30 12:48:07 +02:00
2021-04-27 10:40:29 +02:00
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes[Array.prototype.includes()] documentation at MDN
2021-06-02 20:44:38 +02:00
2023-06-08 09:50:39 +02:00
include::../rspecator.adoc[]