Object.freeze versus const

Earlier, we saw that even if you create objects with const in front of them, a programmer is still able to modify its properties. This is because const creates an immutable binding, that is, you cannot assign a new value to the binding.

Therefore, in order to truly make objects constants (that is, unmodifiable properties), we have to use something called Object.freeze. However, Object.freeze is, again, a shallow method, that is, you need to recursively apply it on nested objects to protect them. Let's clear this up with a simple example.

Consider this example:

var ob1 = {   prop1 : 1,    prop2 : {        prop2_1 : 2     }};Object.freeze( ob1 );const ob2 = {   prop1 : 1,    prop2 : {        prop2_1 : 2     }}ob1.prop1 = 4; // (frozen) ob1.prop1 ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.