JavaScript Const

JavaScript constants are variables, whose values cannot be modified after initialization. We declare them using the keyword const. They are block-scoped just like the let keyword. Their value cannot be changed neither they can be redeclared. Const keyword is part of the es2015 (es6) specification of the javascript.

Declaring a const

We declare constants using the keyword const keyword

Example:

The initial value is a must

The initial value of the const must be specified along with the declaration.

Const is block-scoped

The const is similar to the let keyword. They are local to the code block in which we declare them.

We cannot modify its value

We can assign a value to the const variable at the time of declaration. Once initialized, we cannot modify its value. So if you try to assign a new value to a constant it results in an error.

Similarly, if the const is an object.

Const and object

You cannot assign new content to a const variable. But if the content is an object, then we can modify the object itself.

The following example throws the error Assignment to constant variable when we try to assign a new object to obj variable.

However, you can change the properties of the object itself.

To understand why you need to understand the difference between value types & reference types

There are two types of data types in JavaScript. One is value types (primitive values) & the other one is reference types. The types string, number, Bigint, boolean, undefined, symbol, and null are value types. Everything else is reference types. The primary difference between value types & Reference types is how JavaScript stores them in memory.

JavaScript stores the value types in the variable itself. But in the case of reference type variables, they do not store the value. But they store the reference to the memory location where JavaScript stores the actual values.

JavaScript Const and Objects

Both the code below throws Uncaught TypeError: Assignment to constant variable error as we are assigning a new value.

But you can change the object itself.

The following is an example using arrays.

Cannot access before the declaration

Accessing the const before the initialization results in a ReferenceError. The variable in a “temporal dead zone” from the start of the block until the initialization. You can read more about it from Hoisting in JavaScript.

Cannot Redeclare a const.

Trying to redeclare constant throws the following error. Uncaught SyntaxError: Identifier ‘MaxTry’ has already been declared”.

Summary

You can use const to declare values that do not change. Use let for everything else. But always remember the fact that if const points to an object, then you can change its properties.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top