Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ESLint says array never modified even though elements are pushed into array

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?

like image 455
shashi Avatar asked Jan 14 '16 08:01

shashi


1 Answers

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.

like image 158
Matthisk Avatar answered Oct 12 '22 12:10

Matthisk