Make Your Objects Unchangeable with Object.freeze()
Liz Lam

Liz Lam @grepliz

About: I love open source, coffee and tinkering.

Location:
Oakland
Joined:
Jan 7, 2019

Make Your Objects Unchangeable with Object.freeze()

Publish Date: May 5 '20
8 3

One of the things that confused me initially during my JavaScript learning journey was the const keyword. I thought it was akin to const in C++ where the declared variable would be immutable.

This is not the case in JavaScript.

The const keyword does not create immutability as the name would imply (i.e. no changes allowed), but actually prevents reassignment.

So how do you make JavaScript objects immutable?

That's where Object.freeze() comes in. It is a way to freeze an object and as it implies, a frozen object can not be changed.

Let's look at an example in our browser console.

>> const myinfo = { name: "Liz", title: "Frontend Engineer" }

Now let's change my title via property access:

>> myinfo.title = "Elephant Trainer"
>> myinfo
Object { name: "Liz", title: "Elephant Trainer" }

No problem, as long as we not reassigning anything to myinfo, my name and title are mutable for all to change.

Let's say we do something like this:

>> const myinfo2 = Object.freeze(myinfo)

Object.freeze(myinfo) returns the frozen version of myinfo to myinfo2.

Now before you break out into a song of "Let it Go", it might not be totally obvious that myinfo2 is frozen.

myinfo2.title = "Ballet Dancer" doesn't throw any errors but upon inspection, you will see nothing has changed.

>> myinfo2
Object { name: "Liz", title: "Elephant Trainer" }

In conclusion, if you are looking for a way to make objects unchangeable in JavaScript, const is not the keyword your are looking for. Use Object.freeze() for your immutability needs.

Comments 3 total

  • Josef Biehler
    Josef BiehlerMay 5, 2020

    "final" in Java does not guarantee immutability neither. ;-) Isn't it equal to Javascript's const?

    • Liz Lam
      Liz LamMay 6, 2020

      That is a good point. I was thinking that my example was more nuanced than I stated since final behaves differently with different contexts (i.e. variable vs. method vs. class). I think I will update that portion. Thanks!

  • leastofthese23
    leastofthese23Apr 5, 2022

    Thanks Liz, I had the same confusion coming from C#.

Add comment