Methods to Freeze an Object in JavaScript: Object.freeze(), Object.seal() & Extra




In JavaScript, it’s doable to freeze an object, to make it immutable, and stop it from being modified. This tutorial will present you find out how to do it. You’ll discover ways to freeze an object in JavaScript with Object.freeze(), seal it with Object.seal(), forestall extending it and extra.

Object.seal() methodology

While you need to freeze an object in JavaScript there are two choices you’ll be able to select from. The primary choice is much less restrictive than the second. This selection is about utilizing the Object.seal() methodology. This methodology helps you forestall anybody from including, eradicating or re-configuring present properties of an object.

JavaScript does this by marking all present properties in an object as non-configurable, by altering the property flags. This additionally implies that while you seal an object, you’ll be able to now not change these flags. That is what “re-configuring present properties” means, modifying property flags.

That mentioned, sealing an object nonetheless means that you can change properties that exist in an object. It is because sealing doesn’t change the writable flag. So, except you modify the worth of writable flag you’ll be able to modify present properties. Concerning the syntax. The syntax of Object.seal() is easy.

While you need to seal some particular object you cross that object to the Object.seal() methodology as an argument. This methodology then returns new sealed object. One factor. While you seal an object with Object.seal() you don’t must assign that returned sealed object to a different variable.

Doing it will create new object that’s sealed and assign it to the brand new variable. Nonetheless, it is going to additionally seal the unique object you handed to the Object.seal(). So, because of this, you’ll now have two sealed objects, one unique and one copy.

// Create new object:
const myObj = {
  title: 'Joe Doe',
  age: 37
}

// Seal the "myObj" object:
Object.seal(myObj)

// Verify if object is extensible:
console.log(Object.isExtensible(myObj))
// Output:
// false

// Verify if object is frozen:
console.log(Object.isFrozen(myObj))
// Output:
// false

// NOTE: This can work.
// Attempt to change the worth of "title" property:
myObj.title = 'Jack Ache'

// NOTE: This is not going to work.
// Attempt to add new properties:
myObj.occupation = 'Undercover agent'
myObj.undercover = true

// NOTE: This will even not work.
// Attempt to take away "age" property:
delete myObj.age

// Log the "myObj" object:
console.log(myObj)
// Output:
// {
//   title: 'Jack Ache', // <= Solely worth of "title" prop has modified.
//   age: 37
// }


// Assigning sealed object to new variable (not crucial):
const myObj = {
  title: 'Joe Doe',
  age: 37
}

// Seal the "myObj" object and assign it to new variable:
const myObjSealed = Object.seal(myObj)

// Verify if object is extensible:
console.log(Object.isExtensible(myObjSealed))
// Output:
// false

// Verify if object is frozen:
console.log(Object.isFrozen(myObjSealed))
// Output:
// false

// Attempt to change the worth of "age" in each objects:
myObj.age = 45
myObjSealed.age = 45

// Attempt to add new properties to each objects:
myObj.top = '90 kg'
myObjSealed.top = '90 kg'

// Attempt to take away "age" property:
delete myObj.age
delete myObjSealed.age

// Log the "myObj" object:
console.log(myObj)
// Output:
// {
//   title: 'Joe Doe',
//   age: 45
// }

// Log the "myObjSealed" object:
console.log(myObjSealed)
// Output:
// {
//   title: 'Joe Doe',
//   age: 45
// }

Object.freeze() methodology

The Object.freeze() is the second choice, the extra restrictive. Whereas sealing an object means that you can change present properties, their values, Object.freeze() forbids this. While you freeze an object with Object.freeze() it is going to turn into finally locked. You won’t be able so as to add new properties or take away or modify present.

Along with this, the Object.freeze() methodology additionally prevents anybody from altering the object prototype. The syntax, and means to make use of this methodology, is just like the Object.seal(). The one distinction is the substitute of seal() methodology with freeze(), and in addition the end result.

One other factor Object.freeze() shares with Object.seal() is that you just additionally don’t must assign the returned frozen object to a variable. While you use the Object.freeze() methodology it is going to freeze the unique object. If you happen to additionally assign the returned object to a variable you’ll simply find yourself with two frozen objects.

// Create new object:
const myObj = {
  title: 'Practical Programming in JavaScript',
  creator: 'Luis Atencio'
}

// Freeze the "myObj" object:
Object.freeze(myObj)

// Verify if object is frozen:
console.log(Object.isFrozen(myObj))
// Output:
// true

// NOTE: This is not going to work.
// Attempt to change the worth of "title" property:
myObj.title = 'Practical Programming in JavaScript: Methods to enhance your JavaScript applications utilizing practical methods'

// NOTE: This is not going to work.
// Attempt to add new properties:
myObj.language = 'English'
myObj.format = 'Paperback'

// NOTE: This will even not work.
// Attempt to take away "creator" property:
delete myObj.creator

// Log the "myObj" object:
console.log(myObj)
// Output:
// {
//   title: 'Practical Programming in JavaScript',
//   creator: 'Luis Atencio'
// }


// Assigning frozen object to new variable (not crucial):
const myObj = {
  title: 'Practical Programming in JavaScript',
  creator: 'Luis Atencio'
}

// Freeze the "myObj" object and assign it to new variable:
const myObjFrozen = Object.freeze(myObj)

// Verify if object is frozen:
console.log(Object.isFrozen(myObjFrozen))
// Output:
// true

// Attempt to change the worth of "age" in each objects:
myObj.title = 'Practical Programming in JavaScript: Methods to enhance your JavaScript applications utilizing practical methods'
myObjFrozen.title = 'Practical Programming in JavaScript: Methods to enhance your JavaScript applications utilizing practical methods'

// Attempt to add new properties to each objects:
myObj.format = 'Paperback'
myObjFrozen.format = 'Paperback'

// Attempt to take away "creator" property:
delete myObj.creator
delete myObjFrozen.creator

// Log the "myObj" object:
console.log(myObj)
// Output:
// {
//   title: 'Practical Programming in JavaScript',
//   creator: 'Luis Atencio'
// }

// Log the "myObjFrozen" object:
console.log(myObjFrozen)
// Output:
// {
//   title: 'Practical Programming in JavaScript',
//   creator: 'Luis Atencio'
// }

Object.preventExtensions() methodology

To seal and freeze an object aren’t the one choices to limit manipulations with objects. There’s extra methodology you should use, the Object.preventExtensions(). What this methodology does is it prevents anybody from including new properties to an object. That mentioned, you’ll be able to nonetheless add properties to the article prototype.

The Object.preventExtensions() additionally doesn’t forestall you from deleting present properties. The best way to make use of this methodology is similar as for the earlier two. You cross the article you need to forestall from being prolonged and cross it as an argument to this methodology. New inextensible object shall be returned.

Equally to earlier two strategies, you don’t must assign this returned object to a variable. The Object.preventExtensions() methodology will modify the unique object you handed as argument. If you happen to do assign it, you’ll find yourself with two inextensible objects as a substitute of 1.

// Create new object:
const myObj = {
  language: 'English',
  ethnicity: 'Anglo-Saxons'
}

// Forestall "myObj" from being prolonged:
Object.preventExtensions(myObj)

// Verify if object is extensible:
console.log(Object.isExtensible(myObj))
// Output:
// false

// Attempt to change the worth of present properties:
myObj.language = 'Italian'
myObj.ethnicity = 'Italians'

// Attempt to add new property:
myObj.languageFamily = 'Indo-European'

// Attempt to take away "ethnicity" property:
delete myObj.ethnicity

// Log the "myObj" object:
console.log(myObj)
// Output:
// {
//  language: 'Italian' // <= "ethnicity" has been deleted,
//                      // however no property has been added
// }


// Assigning frozen object to new variable (not crucial):
const myObj = {
  language: 'JavaScript',
  kind: 'high-level'
}

// Forestall "myObj" from being prolonged
// and assign it to new variable:
const myObjInextensible = Object.preventExtensions(myObj)

// Verify if object is extensible:
console.log(Object.isExtensible(myObj))
// Output:
// false

// Verify if object is extensible:
console.log(Object.isExtensible(myObjInextensible))
// Output:
// false

// Attempt to add new property:
myObj.creator = 'Brendan Eich'
myObjInextensible.creator = 'Brendan Eich'

// Attempt to take away property:
delete myObj.kind
delete myObjInextensible.kind

// Log the "myObj" object:
console.log(myObj)
// Output:
// { language: 'JavaScript' }

// Log the "myObj" object:
console.log(myObjInextensible)
// Output:
// { language: 'JavaScript' }

Deeply frozen objects

The Object.freeze() methodology means that you can freeze an object. The Object.seal(), and in addition Object.preventExtensions(), permits to freeze an object partially. That mentioned, there’s a catch. All these strategies carry out solely a “shallow” freeze. These strategies will freeze solely the article itself.

This is not going to be sufficient when you have an object whose properties are additionally objects. On this case, these “internal” or “nested” object is not going to be frozen. Neither of the strategies we mentioned at this time could have any impact on these internal object. This, additionally applies to properties which can be arrays.

One option to remedy that is by utilizing a recursion. You may create a perform. This perform will take an object and return object frozen with the Object.freeze() methodology. Inside this perform, you’ll iterate over all values of the article and verify if any worth is an object. In that case, you’ll name the perform on that worth.

// Create object for testing:
const myObj = {
  title: 'Joe',
  age: 29,
  career: {
    title: 'Programmer',
    expertise: 'senior'
  }
}

// Create perform for deep freezing:
const deepFreeze = obj => {
  // Iterate over all values of supplied object:
  Object.values(obj).forEach(worth => {
    // Verify if every worth is an object:
    if (typeof worth === 'object' && !Object.isFrozen(worth)) {
      // Whether it is and if it isn't frozen
      // name deepFreeze perform on it:
      deepFreeze(worth)
    }
  })

  // Return supplied object as frozen:
  return Object.freeze(obj)
}

// Deep freeze the article:
deepFreeze(myObj)

// Verify if the article itself is extensible:
console.log(Object.isExtensible(myObj))
// Output:
// false

// Verify if the "internal" object is extensible:
console.log(Object.isExtensible(myObj.career))
// Output:
// false

// Attempt to change properties of the article:
myObj.title = 'Jack'

// Attempt to change properties of the "internal" object:
myObj.career.title = 'DevOps architect'
myObj.career.expertise = 'junior'

// Log the "myObj" object:
console.log(myObj)
// Output:
// {
//   title: 'Joe',
//   age: 29,
//   career: { // This "internal" object is remained unchanged.
//     title: 'Programmer',
//     expertise: 'senior'
//   }
// }

Unfreeze?

Now the unhealthy information. While you freeze an object in JavaScript, with the Object.freeze() methodology, you’ll be able to’t unfreeze it. Freezing an object is the last word answer. There is no such thing as a option to reverse this. As soon as some object has been frozen it could possibly’t be unfrozen, or modified in any means. This may occasionally look an excessive amount of, however it’s the easiest way to make sure objects will keep as you left them.

Frozen objects and strict mode

In JavaScript, there are two variants of JavaScript you’ll be able to work with. One is sloppy mode. The opposite is strict mode. Sloppy mode is the traditional mode of JavaScript. It’s the one you’re employed with by default. One distinction between these two is that sloppy mode allow you to do some issues with out throwing an exception, displaying an error.

One instance of that is manipulating with frozen object. While you attempt to do one thing with frozen object that’s forbidden in sloppy mode nothing will occur. The change you need to make is not going to occur and no error will seem. It can fail silently. This is not going to occur should you swap to strict mode.

While you attempt to manipulate with properties of a frozen object JavaScript will throw an exception. This exception shall be some TypeError, which particularly will depend upon what you are attempting to do. If you need JavaScript to throw these exceptions, swap to strict mode by including the 'use strict' assertion.

// Use strict mode:
'use strict';

// Create an object:
const myObj = {
  title: 'Practical Programming in JavaScript',
  creator: 'Luis Atencio'
}

// Freeze the "myObj" object:
Object.freeze(myObj)

// Attempt to change the worth of "title" property:
myObj.title = 'Practical Programming in JavaScript: Methods to enhance your JavaScript applications utilizing practical methods'
// Output:
// TypeError: Can't assign to learn solely property 'title' of object '#<Object>'

// Attempt to add new properties:
myObj.language = 'English'
myObj.format = 'Paperback'
// Output:
// TypeError: Can't add property language, object just isn't extensible

// Attempt to take away "creator" property:
delete myObj.creator
// Output:
// TypeError: Can't delete property 'creator' of #<Object>

Conclusion: Methods to freeze an object in JavaScript

Freezing objects in JavaScript, both utterly or partially, is straightforward. It’s also straightforward to stop objects solely from being prolonged by including new properties. With a bit code, you can even guarantee frozen objects are deeply frozen. I hope that this tutorial helped you perceive find out how to do all these items.

If you happen to favored this text, please subscribe so you do not miss any future submit.








If you would like to help me and this weblog, you’ll be able to turn into a patron, or you should purchase me a espresso 🙂







Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#Freeze #Object #JavaScript #Objectfreeze #Objectseal