Variables declared with const
cannot be reassigned using the assignment operator.
The const
declaration creates an immutable reference to a value. This does not mean the value it holds is immutable, but the
identifier cannot be reassigned. For example, if the constant is an object, its properties can still be altered. Use Object.freeze()
to
make an object immutable.
You must always specify an initializer in a const
declaration as it can not be changed later. Trying to declare a constant without an
initializer (const foo;
) will throw a SyntaxError.
Trying to reassign a constant will throw a TypeError. In a non-ES2015 environment, it might simply be ignored.
const pi = 3.14;
pi = 3.14159; // Noncompliant: TypeError: invalid assignment to const 'pi'
If a variable will need to be reassigned, use let
instead.
let pi = 3.14;
pi = 3.14159;