Deep freeze an object recursively
Deep freeze an object recursively in JavaScript so nested objects and arrays become read only too, and see the strict mode errors it produces.
Object.freeze stops at the first level. Nested objects can still be changed, so a frozen config is not really frozen. Freeze the children as well.
'use strict';
const deepFreeze = (obj) => {
Object.freeze(obj);
for (const value of Object.values(obj)) {
if (value && typeof value === 'object' && !Object.isFrozen(value)) deepFreeze(value);
}
return obj;
};
const config = deepFreeze({ db: { host: 'localhost', ports: [5432] } });
try {
config.db.host = 'other';
} catch (error) {
console.log(error.message);
}
try {
config.db.ports.push(6432);
} catch (error) {
console.log(error.message);
}Cannot assign to read only property 'host' of object '#<Object>'
Cannot add property 1, object is not extensibleThe object is frozen before its children are visited, so a cycle stops at the first object that is already frozen and does not loop forever. In strict mode, which the first line turns on, writing to a frozen object throws. In sloppy mode the write is ignored without any message. See Object.freeze.
Freezing a non-empty typed array throws, and Map and Set can still be changed through their methods, because freezing does not touch their internal data. Freeze marks the object; it does not make it deeply immutable by type.