Javascript object freezing

Habibul Hasan
Analytics Vidhya
Published in
3 min readDec 30, 2019
source: https://www.clearboxseo.com/wordpress-javascript-seo-google-search-index/

Object.freeze() is for Objects, it takes an object as a parameter and returns back that same object with new behavior that can not be modified. That means you can not add new properties or modify the values of that object.

Once you freeze an Object you are not allowed to do the things done on try block, it will let you run your code without any error but will not have any effect on Riders object!

Now let’s see what happens when we try to change Frozen Objects Object Property (i.e address has a nested object as a value)

Nested rules after Object Freeze

Like the previous example when a js frozen Object’s property has a value of Object type,
1. you can not change the inner object's property value.
2. Can not add more property with it.

Now, what happens details property? On the second layer, you can change anything! You are allowed to change the value of add new properties, see example below

Changeable nested properties

you probably will want to achieve this with const, const will allow to change/modify property values and will allow adding a new property, That means there is no use of declaring Object as const, see code below

Some times we just want to prevent clients to add new properties with an existing object but let them change its property value, to achieve this behavior we use to seal. when we seal an object its already defined values can be modified but no new values can be added or deleted. see code below

  • Freeze: makes the object immutable, meaning no change to the defined property allowed, unless they are objects. it returns a new object
  • Seal: prevent the addition of properties, however, defined properties still can be changed. It returns the same object with its property writable value as true

Read more on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

CAN YOU GUESS THE OUTPUT?

get me at https://www.linkedin.com/in/hirahasan/

--

--

Habibul Hasan
Analytics Vidhya

Detailed oriented human being! love to code , ride and travel