'number' is never reassigned. Use 'const' instead. (prefer-const)

Oto_Shan picture Oto_Shan · Feb 9, 2018 · Viewed 17.2k times · Source

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)

Answer

Cristian S. picture Cristian S. · Feb 9, 2018

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