79 lines
1.8 KiB
Plaintext
Raw Normal View History

== 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.
=== 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";
}
}
----
=== 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";
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use "indexOf" or "includes" (available from ES2016) instead.
=== Highlighting
"in" expression
'''
== Comments And Links
(visible only on this page)
=== 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.
endif::env-github,rspecator-view[]