I am converting some existing code to follow ECMA script and I am using ESLint to follow a coding standard. I have the following ecmascript method
static getArrayOfIndices(text, char) {
let resultArray = [];
let index = text.indexOf(char);
const lastIndex = text.lastIndexOf(char);
while (index <= lastIndex && index !== -1) {
resultArray.push(index);
if (index < lastIndex) {
index = text.substr(index + 1).indexOf(char) + index + 1;
} else {
index = lastIndex + 1999; // some random addition to fail test condition on next iteration
}
}
return resultArray;
}
For the declaration of resultArray, ESLint throws the error
ESLint: `resultArray` is never modified, use `const`instead. (prefer-const)
But since elements are being pushed into the array, isn't it being modified?
To understand this error you must understand that const
declared variables hold read-only references to a value. But it does not mean that the value it holds is immutable [mdn article].
Since you are only changing members of the variable, but not performing a reassignment on the binding the prefer-const
rule of es-lint warns you that a const
declared variable could be used instead of a let
declared variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With