const
Declares a variable that cannot be reassigned.
Available since: ES2015
Syntax
const name = valueExamples
A constant:
const pi = 3.14;
console.log(pi * 2);Output:
6.28Reassigning fails, changing the object works:
const user = { name: 'Anna' };
user.name = 'Oleg';
console.log(user.name);
try {
user = {};
} catch (error) {
console.log(error.name);
}Output:
Oleg
TypeErrorNotes
const forbids assigning a new value to the variable but does not make the object immutable. For that there is Object.freeze().
Declare variables with const by default and with let only if the value will change.
See also
- let — Declares a variable whose value can change.
- var — The legacy way to declare a variable.
- Object.freeze — Prevents any changes to an object.
In the tutorial
- Variables — How to declare variables in JavaScript with let and const, name them and insert them into strings.