The in
operator is used to check if a property is in an object or its 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.
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()
.
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";
}
}