
One of the things that confused me initially during my JavaScript learning journey was theconst
keyword. I thought it was akin toconst
in C++ where the declared variable would be immutable.
This is not the case in JavaScript.
Theconst
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 whereObject.freeze()
comes in. It is a way tofreeze 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">> myinfoObject { name: "Liz", title: "Elephant Trainer" }
No problem, as long as we not reassigning anything tomyinfo
, myname
andtitle
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 ofmyinfo
tomyinfo2
.
Now before you break out into a song of "Let it Go", it might not be totally obvious thatmyinfo2
is frozen.
myinfo2.title = "Ballet Dancer"
doesn't throw any errors but upon inspection, you will see nothing has changed.
>> myinfo2Object { 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. UseObject.freeze()
for your immutability needs.
Top comments(3)

- LocationWeiden, Germany
- EducationBachelor of Science
- Joined
"final" in Java does not guarantee immutability neither. ;-) Isn't it equal to Javascript's const?

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

- EducationUniversity of Phoenix
- WorkFull Stack Developer
- Joined
Thanks Liz, I had the same confusion coming from C#.
For further actions, you may consider blocking this person and/orreporting abuse