What really is a constant in Javascript with object ?

What really is a constant in Javascript with object ?

ยท

3 min read

Introduction

I have been working as a frontend developer in last 6 years of my full time job and using most recent ECMAScript standard and it has lots of advantages and new features. One of them is to able to define constants. In Javascript this was not possible to do until ES6 came out and introduced the const keyword.

When we initialize a variable with the const keyword in javascript, we expect it to be immutable which means its value cannot be changed and its generally true for simple values like numbers, booleans and strings. However, things get complicated, when it comes to objects and arrays.

What is a constant in Javascript?

The const keyword allows us to assign a name to a value which is similar like let and var in javascript. However, once we assign a value, we cannot reassign another value.

Lets me demonstrate with example below:

const name = "Jhon Doe"
name = "Lorem"
console.log(name)

When use above code in our browser console, the console throw an error showing assignment to constant variable.

What is not a constant ?

In javascript, the objects and array are stored by refrence but not by value, so when we start working with objects and array, actually we are declaring a constant reference to that object or array. This means that, we cannot reassign the variable to a different object or array, but we can still mutate the object or array itself.

const person = {firstName:"Jhon", lastName:"Doe"};

//Error: Assignment to constant variable
person = {firstName:"Lorem", lastName:"Ipsum"};

// This works
person.firstName = "Lorem";
person.lastName = "Ipsum";

console.log(person.firstName+' '+person.lastName); // Result "Lorem Ipsum"

In the above code, we are trying to reassign person variable to a different object but it will throw an error because person is constant variable.

But in the second example, we are mutating the person object by changing value of firstName and lastName property. It is working fine because we are not reassigning the person variable itself only assigning to its property.

Example in Diagram

How to make an object immutable ?

We can make object immutable by using Object.freeze() which is a method or function that prevents any changes to properties of object including nested objects.

Lets me demonstrate with example below:

const person = {firstName:"Jhon", lastName:"Doe"};
Object.freeze(person);

person.firstName = "Lorem";
person.lastName = "Ipsum";

console.log(person.firstName+' '+person.lastName); 
// Result "Jhon Doe"

Object.freeze() is a shallow freeze, which means the nested objects can still be modified. To make nested objects immutable, we can use recursion.

function makeObjectComplteFreeze(obj){
    Object.freeeze(obj);
    for(let key in obj){
        if(typeof obj[key] === 'object'){
            makeObjectComplteFreeze(obj[key])
        }
}

const person = { 
                name:{
                    first:"Jhon",
                    last:"Doe"
                },
                age: 30
};
makeObjectComplteFreeze(person);

In the above example, to make whole object immutable simply pass the object to that function.


Conclusion

The const keyword is not constant when it comes to objects and arrays, const only prevents us from reassigning the variable to a different object or array. We can still mutate the object or array itself.

Additionally, we can use Object.freeze() method to make an object immutable which will prevents changes to the properties of objects including nested objects.

Feel free to share your thoughts and opinions and leave me a comment if you have any problems or questions. ๐Ÿ˜Ž๐Ÿ˜Ž

I hope you liked it and learned something!

Happy Coding!!

ย