10

Why in this case eslint 4.17.0 i have error number is never reassigned. Use 'const' instead. (prefer-const). Why i need to use const? Please, explain me i can't understand.

let test = {
    'number': 1,
    'string': 'asd',
};
test.number = 99;

console.log(test.number);
// output: 99

ecmascript

 {
    "parser": "babel-eslint",
    "env": {
        "browser": true
    },
    "extends": [
        "google"
    ],
    "rules": {
        "prefer-const": 2

    },
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module"
    }
}

eslint problem

[eslint] 'test' is never reassigned. Use 'const' insted. (prefer-const)
Oto_Shan
  • 113
  • 1
  • 1
  • 5
  • 2
    1. Show us your lint rules. 2. Show exact error message. – lolbas Feb 09 '18 at 13:51
  • https://eslint.org/docs/rules/prefer-const – freedomn-m Feb 09 '18 at 14:03
  • 1
    It's because `test` is *not* changed. You're changing `test.number`, not `test`. – freedomn-m Feb 09 '18 at 14:38
  • 2
    Also, your error message does not match your question title. One says `test` (correctly) the title says "number" which is changed and is not in the warning. – freedomn-m Feb 09 '18 at 14:39
  • Dang, I was looking for this rule. Somehow VSCode stopped suggesting this to me. Looks like it was just this project where I don't have my usual eslint rules ‍♂️. Without eslint it's like missing an eye. – Qwerty Dec 20 '22 at 22:23

2 Answers2

5

ES6 const does not indicate that a value is ‘constant’ or immutable. A const value can definitely change. The following is perfectly valid ES6 code that does not throw an exception.

const foo = {};
foo.bar = 42;
console.log(foo.bar);
// → 42

In your case, if you know that you are gonna change the properties, try using let.

Take a look here: https://mathiasbynens.be/notes/es6-const

Cristian S.
  • 937
  • 5
  • 13
  • 1
    My mistake the example is with leth, why eslint warning me that need to be const? – Oto_Shan Feb 09 '18 at 14:28
  • 3
    @Oto_Shan because `let` assumes that the variable value will be changed at some point of execution which in your example is not happening. – lolbas Feb 09 '18 at 14:30
2

From ESlint Docs:

If a variable is never modified, using the const declaration is better. Const declaration tells readers, “this variable is never modified,” reducing cognitive load and improving maintainability.

        /*eslint prefer-const: 2*/
/*eslint-env es6*/

let a = 3;               /*error 'a' is never modified, use 'const' instead.*/
console.log(a);

// `i` is re-defined (not modified) on each loop step.
for (let i in [1,2,3]) {  /*error 'i' is never modified, use 'const' instead.*/
    console.log(i);
}

// `a` is re-defined (not modified) on each loop step.
for (let a of [1,2,3]) { /*error 'a' is never modified, use 'const' instead.*/
    console.log(a);
}
Max Sherbakov
  • 1,817
  • 16
  • 21