Search⌘ K

const

Explore how the const keyword in JavaScript defines variables that cannot be reassigned, differences from let, and the limitations in protecting object internals. Understand how to make objects immutable using Object.freeze and the impact of strict mode in enforcing immutability.

The const keyword is used to define a variable whose value shouldn’t change.

Difference between let and const

If you intend to modify the value in a variable, define it using let; otherwise, define it using const.

Example

Here’s an example that shows the difference between using let and const:

Javascript (babel-node)
//BROKEN CODE
'use strict';
let price = 120.25;
const tax = 0.825;
price = 110.12;
tax = 1.25;

Explanation

There’s no issue changing the value of the price variable. However, since tax is defined as a constant, we will get a runtime error when we try to modify the value:

tax = 1.25; 

So, we get the following error message: TypeError: Assignment to constant variable.

Reach of const

Before we declare const as one of the most awesome features in modern JavaScript, let’s understand its limitations.

Limitations of const

Only primitive values, like numbers, and references to objects are protected from change. The actual object that the reference refers to does not receive any protection from the use of ...