How to Declare Constants in JavaScript?

ES6 provides a new way of declaring a constant by using the const keyword which creates a read-only reference to a value:

const CONSTANT_VALUE = "someValue";

This works in almost all browsers.

Capitalization indicates that some values should be constant.

Local variables with block scope can be declared with const. Assuming, we have a constant variable CONSTANT_VALUE. After declaring a value like a constant variable, you can’t assign a new value to it:

Javascript const keyword
// declared ‘CONSTANT_VALUE’ as a constant variable. const CONSTANT_VALUE = 200; // Assigning a new value to `CONSTANT_VALUE` will fail since ‘CONSTANT_VALUE’ is a constant variable CONSTANT_VALUE = 0; console.log(CONSTANT_VALUE);
Javascript const keyword
// declared ‘CONSTANT_VALUE’ as a constant variable. const CONSTANT_VALUE = 200; CONSTANT_VALUE++; console.log(CONSTANT_VALUE);
Javascript const keyword
// declared ‘CONSTANT_VALUE’ as a constant variable. const CONSTANT_VALUE = 200; // The below declarations won’t work var CONSTANT_VALUE = 0; console.log(CONSTANT_VALUE);

The constant cannot change through re-assignment constant cannot be re-declared. Const can be changed if it is an object because when you're adding to an array or object you're not re-assigning or re-declaring the constant, it's already declared and assigned, you're just adding to the "list" that the constant points to. So this works fine:

Javascript const keyword for objects
const obj = {}; obj.name= 'John'; console.log(obj); // {name : 'John'} obj.name = 'Jack'; console.log(obj); // {name : 'Jack'}
Javascript const keyword for array
const arr = []; arr.push('elem1'); console.log(arr); // ['elem1'] arr.unshift("elem2"); console.log(arr); // ['elem2', 'elem'] arr.pop(); console.log(arr); // ['elem2']

The const Variable

ES2015 introduced two new JavaScript keywords: let and const. Variables defined with const behave like let variables, except they cannot be re-assigned. In the programming world, a constant is something that does not change. The const creates a constant that is a read-only reference to a value, which does not mean the value it holds is immutable. It only indicates that the variable identifier cannot be re-assigned.