ESLint prefer-const error with conditional reassign

424 views Asked by At

Is there a special way to reassign let within conditional statement to avoid keep getting prefer-const eslint error?

My code:

let jsx = [];

if (a === b) {
  jsx.push(
    <div>
      xxx
    </div>
  );
}

jsx.push(<div>yyy</div>);

=== UPDATE === Sorry for the confusing, actually it is not a reassign operation.

2

There are 2 answers

0
Ori Drori On BEST ANSWER

You can use const because you're not reassigning the jsx variable, just pushing into the array that it points to:

  const jsx = [];

  if (a === b) {
    jsx.push(
      <div>
        xxx
      </div>
    );
  }

  jsx.push(<div>yyy</div>);
0
Michał Perłakowski On

You're not reassigning the jsx variable, you're only modifying it. Variables declared using const can be modified, so you can just replace let with const.

From MDN:

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered.

Example:

const arr = [];
arr.push(42);
console.log(arr);