r/ProgrammerTIL • u/greynoises • Apr 10 '18
Javascript [JavaScript] TIL you can prevent object mutation with Object.freeze()
You can make an object immutable with Object.freeze(). It will prevent properties from being added, removed, or modified. For example:
const obj = {
foo: 'bar',
}
Object.freeze(obj);
obj.foo = 'baz';
console.log(obj); // { foo: 'bar' }
obj.baz = 'qux';
console.log(obj); // { foo: 'bar' }
delete obj.foo;
console.log(obj); // { foo: 'bar' }Notes:
- You can check if an object is frozen with
Object.isFrozen() - It also works on arrays
- Once an object is frozen, it can't be unfrozen. ever.
- If you try to mutate a frozen object, it will fail silently, unless in strict mode, where it will throw an error
- It only does a shallow freeze - nested properties can be mutated, but you can write a
deepFreezefunction that recurses through the objects properties
63
Upvotes
View all comments
Show parent comment
1
u/mezzoEmrys Apr 10 '18
If garbage collection works normally I'm on board with it then as a good practice, but the fact it can't be manually deleted put me on edge.