ES2015 (ES6) introduced the const keyword to define a new variable. The value of a constant (const) can't be changed through reassignment
- Variables defined with const cannot be Redeclared.
- Variables defined with const cannot be Reassigned.
- Variables defined with const have Block Scope.
The const variable cannot be reassigned.
Incorrect:
const x = 12;
x = 13;
x += 1;
// Uncaught TypeError: Assignment to constant variable.
Variables defined with const cannot be Redeclared.
const x;
x = 5; // Can't Do this
// Uncaught SyntaxError: Missing initializer in const declaration
Variables defined with const have Block Scope.
const a = 2; // You can use the same name out of Block
{
const a = 3; // You can use same name in Block
console.log(a);
}
console.log(a);
OUTPUT:
3 2
- There is no error
Const Array:
// You can create a constant array:
const name = ["a", "b", "c"];
// You can change an element:
cars[0] = "d";
// You can add an element:
cars.push("e");
But you can’t reassign the array
name = ["d","e","f"]