Making Objects Immutable in JavaScript
If the below code blocks do not show up properly due to a recent Tumblr change. View them directly at https://obscurejavascript.tumblr.com/
By default any user created in JavaScript can have most of its properties modified. In some cases this can lead to confusing errors like a config setting object being updated via event driven code in a very hard to track down way. To avoid this property modifications of any kind can be prevented.
Firstly here is an example of the function in action:
const config = immutable({ id: 'test-1', adminUsers: [ { id: 'user-1', name: 'User 1' }, { id: 'user-2', name: 'User 2' }, { id: 'user-3', name: 'User 3' } ], }); // Simulate some event driven code doing an update setTimeout(() => { // This will either give an error in strict mode or newer environments or just // fail to do anything silently in other situations. config.adminUsers[1].name = 'User 2+'; }, 200); // Simulate some event driven code checking the config setTimeout(() => { console.log('User 2:', config.adminUsers[1]); }, 500);
This is the immutable:
function immutable(obj) { // Simple implementation to demonstrate the point. This is just example code. for (const property in obj) { if (obj.hasOwnProperty(property)) { const value = obj[property]; if (Array.isArray(value) || typeof value === 'object') { obj[property] = immutable(value); } } } return Object.freeze(obj); }
The immutable function simply goes through each property of an object and then freezes it. Note that Object.freeze will only freeze the top level properties. To freeze sub objects, the object property values need to be looped through. Since the above is just example code, it only goes deeper when an array or basic object of some form is encountered. Some edge cases may be missed.
I find this type of function very useful when trying to track down hard to follow modifications. I just set it on an object that gets modified in a hard to track down way and then a stack trace gives me exactly where that happened.
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2020/immutable.js








