DEV Community

Cover image for Object Immutability in Javascript
Emmanuel Onah
Emmanuel Onah

Posted on • Updated on

Object Immutability in Javascript

In this session, we will be focusing on object immutability.

TABLE OF CONTENT

  1. Immutability
  2. seal() method
  3. freeze() method

Immutability

Immutability simply means can't be modified after creation.

In javascript, value immutability can simply be achieved using const keyword to declare a variable. Unfortunately, const keyword can not make an object immutable.
For Example
Alt Text

Alt Text

So to achieve object immutability, we simple use the freeze() method which helps in hindering an object from being tampered with.

2.Object.seal({theObject: ...}):

this method hinders the extension of an object length. That is, you can not add new property or method to an already sealed object.
For Example:
const names = {
nameOne:'creativeAdams',
nameTwo:'creativeJerry'
}
Object.seal(names);
//or you can use the below method to
Object.preventExtensions(names);

Alt Text

Alt Text

3. Object.freeze({theObject:...}):

this method hinders the changing of an existing property or method and an extension of an object.
For Example:
const names = {
nameOne:'creativeAdams',
nameTwo:'creativeJerry'
}
Object.freeze(names);

Alt Text

Top comments (0)