Are There Constants in JavaScript?

The answer is yes — there are ways to use 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.
var CONSTANT_VALUE = "someValue";

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

// declared ‘a’ as a constant variable.
const a = 200;
// Assigning a new value to `a` will fail since ‘a’ is a constant variable
a = 0;
// The below declarations won’t work
var a = 0;

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.

Do you find this helpful?

Related articles