JavaScript

When to Use “const” With Objects in JavaScript?

const” is a keyword in JavaScript used for declaring variables that are immutable means they cannot be reassigned to another value. It does not define a constant/fixed value. It specifies a constant reference to a value. It acts differently when interacting with objects. When you declare an object with “const”, it is not immutable, you can still change its properties. However, const restricts reassigning the variable to another object. JavaScript code that uses “const” with objects is easier to maintain and less likely to have errors from careless variable reassignments.

This blog will explain the use of “const” with objects in JavaScript.

Use of “const” With Objects in JavaScript

The “const” with objects in JavaScript allows modification of the object’s properties but does not allow reassignment of the variable to another object.

Example

Create or declare an object named “obj” using the “const” keyword with three attributes “name”, “age”, and “hobby”:

const obj = {

name: "Mili",

age: 24,

hobby: "Book Reading"

}

Access the value of the object attribute “hobby” using the dot “.” operator and print on the console with the help of the “console.log()” method:

console.log(obj.hobby);

The output indicates that we have successfully accessed the value of the “const” object property named “hobby”:

Here, we will modify the value of the “const” object property named “hobby” to “Painting” and print it on the console:

obj.hobby = "Painting";

console.log(obj.hobby);

The value has been successfully updated. It indicates that the properties of the const objects can easily be updated:

But the “const” will not allow reassigning the variable to another object. Here, we will assign a new object to the “const” object “obj”:

obj = {

name: "Emma",

age: 26,

hobby: "Traveling"

}

Print the “obj” as an updated object:

console.log(obj);

Output

That’s all about the usage of the “const” with objects in JavaScript.

Conclusion

The variables with the “const” keyword in JavaScript are immutable but the object with “const” is not immutable, you can still modify its properties. However, const does not allow reassigning the variable to another object. This blog explained the use of “const” with objects in JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.