2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-07-11 10:42:13 +02:00
The ``++in++`` operator is used to check if a property is in an object or its https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain[prototype chain].
2021-04-28 16:49:39 +02:00
2023-07-11 10:42:13 +02:00
When used on an array, it will compare against the indexes of the array, not the values. This is likely not to be the expected behavior.
2021-04-28 16:49:39 +02:00
2023-07-11 10:42:13 +02:00
[source,javascript,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
2023-07-31 18:01:52 +02:00
function func() {
2023-07-11 10:42:13 +02:00
const arr = ["a", "b", "c"];
2021-04-28 16:49:39 +02:00
2023-07-11 10:42:13 +02:00
const expectedValue = "b";
if (expectedValue in arr) { // Noncompliant: will be always false
2021-04-28 16:49:39 +02:00
return expectedValue + " found in the array";
} else {
return expectedValue + " not found";
}
}
----
2023-07-11 10:42:13 +02:00
Use the method `Array.prototype.includes()` to determine whether an array contains a certain value. If the actual intention is to check for an array slot, use ``++Object.prototype.hasOwnProperty()++``.
2021-04-28 18:08:03 +02:00
2023-07-11 10:42:13 +02:00
[source,javascript,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
function func() {
2023-07-11 10:42:13 +02:00
const arr = ["a", "b", "c"];
2021-04-28 16:49:39 +02:00
2023-07-11 10:42:13 +02:00
const expectedValue = "b";
2021-04-28 16:49:39 +02:00
if (arr.includes(expectedValue)) {
2023-07-31 18:01:52 +02:00
return expectedValue + " found in the array";
2021-04-28 16:49:39 +02:00
} else {
return expectedValue + " not found";
}
}
----
2021-04-28 18:08:03 +02:00
2023-07-11 10:42:13 +02:00
== Resources
=== Documentation
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in[MDN - `in` operator]
* link:++https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in++[MDN - ``++for...in++``]
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes[MDN - `Array.prototype.includes()`]
2021-04-28 18:08:03 +02:00
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Use "indexOf" or "includes" (available from ES2016) instead.
=== Highlighting
"in" expression
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== on 7 May 2018, 13:56:14 Stas Vilchik wrote:
\[~alexandre.gigleux] JavaScript is not a compiled language, so please remove the word "compile" from the description.
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]