How to use 'const' keyword in JavaScript?


We use the const keyword in JavaScript to declare variables whose value can be initialized only at the time of declaration. It is similar functionality of declaring variables as the other keywords provided in JavaScript i.e. var and let. const is short for constant, meaning that the value that resides in the variable is unchangeable.

The const keyword in JavaScript

It is used to declare variables in JavaScript. The variables created using const follow certain rules.

  • The variable is block scoped. This means that the scope(lifetime) of the variable depends on the place where it has been declared. This follows the same rules of scope as the let keyword.

  • The value of the const variable should be provided at the time of declaration only. This is because of the fact that once declared the value stored in the const variable cannot be changed.

  • However, an array or object declared using the const keyword can be modified.

  • Any attempt to modify or access the const variable before its initialization results in a reference error. The variable is said to be in a Temporal Dead Zone (TDZ) if the declaration line is yet to be executed. This behavior is different from the var keyword.

A const keyword holds a read-only permission for the variable. This means that, under the hood, the variable rather than the value stored in that variable is constrained to not change. Any attempt to write the variable throws an error because of no write permission on the variable.

Syntax

const NUM = 10;

This creates a constant variable NUM with the value of 10. Note that it is a common convention to write const variables in uppercase. This is to emphasize that the variable is constant and should not be modified.

Let’s see the working of const keyword with an example.

Example 1

Here we are going to create a const variable and then try to change its value. This will throw an error "Assignment to constant variable" which we will handle using the try-catch block.

Let’s look at the code for same.

<!DOCTYPE html> <html> <body> <div id="result"></div> </body> <script> const NUM = 10; var text = ""; for (let NUM = 0; NUM < 10; NUM++) { text += NUM + ","; } text += "<br>" try { NUM = 20; } catch (err) { text += err.message; } document.getElementById("result").innerHTML = text; </script> </html>

In the above code, there are two main things to notice. One is the block-scoped nature of the const variable. This lets us define another variable using the same name NUM without any conflict. This is due to the fact that let creates block-scoped variables. So the NUM inside of for loop is a non-const variable having the same identifier name as the const variable. The NUM created inside the loop works independently of the const variable which is globally scoped because it was declared outside of every block.

The second thing to note is the error that is thrown when we try to reinitialize the value of the const variable NUM. This is in accordance with how const works.

Note that if we try to declare a variable using the var keyword having the same name as the const variable, then it will throw an error because variables declared using the var keyword has a global scope, and this creates conflict.

Also note that if we try to declare a variable without initializing it, it throws a "Missing Initializer in const declaration" error.

The const keyword is very often used to declare arrays and objects. This is because it doesn’t allow reassignment of the object variable but at the same time allows the flexibility to modify the properties of the object.

Here’s an example of how to use the const keyword with objects in JavaScript.

Example 2

Here we are going to create an object using the const keyword having two properties name and age. We then try to modify the age property. This will work well because we are dealing with objects rather than primitive variables. Let’s look at the code for the same.

<!DOCTYPE html> <html> <body> <div id="result"></div> </body> <script> var text = ""; const student = { name : "Jane Doe", age : 27 } student.age = 29; text += student.name + "<br>"; text += student.age + "<br>"; document.getElementById("result").innerHTML = text; </script> </html>

In the above code, as is visible in the output as well, the age property can be successfully modified.

Conclusion

const keyword is a big help in preventing unwanted users from changing your variable, as well as keeping track of values that remain constant throughout program execution.

Updated on: 10-Nov-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements