33 lines
925 B
Plaintext
Raw Normal View History

== 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.
2020-06-30 12:48:07 +02:00
[source,javascript,diff-id=1,diff-type=noncompliant]
2020-06-30 12:48:07 +02:00
----
let arr = ["blue", "red"];
2020-06-30 12:48:07 +02:00
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.
2020-06-30 12:48:07 +02:00
[source,javascript,diff-id=1,diff-type=compliant]
2020-06-30 12:48:07 +02:00
----
let arr = ["blue", "red"];
2020-06-30 12:48:07 +02:00
if (arr.includes("blue")) {
2020-06-30 12:48:07 +02:00
// ...
}
----
This rule raises an issue when an `indexOf` value retrieved from an array is tested against `> 0`.
== Resources
=== Documentation
2020-06-30 12:48:07 +02:00
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes[``++Array.prototype.includes()++``]
2023-06-08 09:50:39 +02:00
include::../rspecator.adoc[]