org.sonar.l10n.javascript.rules.javascript.S4619.html Maven / Gradle / Ivy
Why is this an issue?
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";
}
}
Resources
Documentation
- MDN web docs -
in
operator
- MDN web docs -
for...in
- MDN web docs -
Array.prototype.includes()
© 2015 - 2024 Weber Informatics LLC | Privacy Policy