2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
The ``++in++`` operator used on an array is valid but the code will likely not have the expected behavior. The ``++in++`` operator deals with the indexes of the array, not with the values.
If checking for an array slot is indeed desired, using ``++hasOwnProperty++`` makes the code intention clearer.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
function func1() {
let arr = ["a", "b", "c"];
let expectedValue = "b";
if (expectedValue in arr) { // Noncompliant, will be always false
return expectedValue + " found in the array";
} else {
return expectedValue + " not found";
}
}
function func2() {
let arr = ["a", "b", "c"];
let expectedValue = "1"; // index #1 is corresponding to the value "b"
if (expectedValue in arr) { // Noncompliant, will be always true because the array is made of 3 elements and the #1 is always there whatever its value
return expectedValue + " found in the array";
} else {
return expectedValue + " not found";
}
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
function func() {
let arr = ["a", "b", "c"];
let expectedValue = "b";
if (arr.includes(expectedValue)) {
return expectedValue + " was found in the array";
} else {
return expectedValue + " not found";
}
}
----
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[]