Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

const

Declares a variable that cannot be reassigned.

Available since: ES2015

Syntax

const name = value

Examples

A constant:

const pi = 3.14;
 
console.log(pi * 2);

Output:

6.28

Reassigning 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
TypeError

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.