69 lines
2.0 KiB
Plaintext
69 lines
2.0 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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].
|
|
|
|
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.
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
function func() {
|
|
const arr = ["a", "b", "c"];
|
|
|
|
const expectedValue = "b";
|
|
if (expectedValue in arr) { // Noncompliant: will be always false
|
|
return expectedValue + " found in the array";
|
|
} else {
|
|
return expectedValue + " not found";
|
|
}
|
|
}
|
|
----
|
|
|
|
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()++``.
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
function func() {
|
|
const arr = ["a", "b", "c"];
|
|
|
|
const expectedValue = "b";
|
|
if (arr.includes(expectedValue)) {
|
|
return expectedValue + " found in the array";
|
|
} else {
|
|
return expectedValue + " not found";
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in[`in` operator]
|
|
* MDN web docs - link:++https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in++[``++for...in++``]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes[`Array.prototype.includes()`]
|
|
|
|
|
|
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[]
|