Yesterday I learned you can have immutable objects in JavaScript.
Constant values of course are nothing new (e.g. const PI = 3.14
), at least for simple values. But for objects, the name of the constant only affects which object the name refers to, not the value of the object’s members.
const a = { num: 5}
console.log(a.num);
// outputs: 5
a.num = 10;
console.log(a.num);
// outputs: 10
a = {}
// TypeError: Assignment to constant variable.
So it turns out you can make an object immutable by passing it to Object.freeze()
.
So if we take the previous example and freeze the object, changing the property’s value doesn’t work.
const a = { num: 5}
console.log(a.num);
// outputs: 5
Object.freeze(a);
a.num = 10;
console.log(a.num);
// outputs: 5
The thing that bothers me about this is the attempted assignment fails silently. That opens the possibility of some hard to find bugs.
Start the code with 'use strict'
, and now there’s an explicit runtime error.
'use strict'
const a = { num: 5}
console.log(a.num);
// outputs: 5
Object.freeze(a);
a.num = 10;
// TypeError: Cannot assign to read only property 'num' of object
The other thing to note is that, much like const
does for variables, freeze()
only affects the values of simple properties. If a property refers to an object, that object’s properties won’t be frozen.
The examples in the Mozilla documentation includes a discussion of “shallow freezing” a deepFreeze()
example method demonstrating a recursive technique for freezing object members recursively.
(Cover image via WikiMedia commons, used under Creative Commons Attribution-ShareAlike 1.0 Generic)