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?
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?
Share Improve this question asked Jan 14, 2016 at 8:16 shashishashi 4,6969 gold badges54 silver badges82 bronze badges 2- 7 But it stays the same array object, so the pointer to that object is a constant. – Sirko Commented Jan 14, 2016 at 8:21
- 1 Ah! Even though the contents of the object may change, the reference /pointer to that object remains the same so it is preferred to use const. If the reference was being changed, e.g. resultArray = someOtherArray, then using let would be fine. Got it! – shashi Commented Jan 14, 2016 at 8:31
1 Answer
Reset to default 34To 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.