r/ProgrammerTIL • • 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 deepFreeze function that recurses through the objects properties

MDN documentation for Object.freeze()

63 Upvotes

18 comments sorted by

View all comments

Show parent comment

1

u/jjokin Apr 11 '18

It's useful for:

  • objects that are/store constants
  • immutable objects (like some functional programming)

-1

u/mezzoEmrys Apr 11 '18

yeah, which all makes sense, except that I thought there was a cost of the object never being deleted or garbage collected, which would be an incredible stopping block for using either of those