AppDividend
Latest Code Tutorials

Javascript Object Freeze Example | Object.freeze() Tutorial

0

Javascript Object Freeze Example | Object.freeze() Tutorial is today’s topic. The Object.freeze() method freezes an object. The frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed.

Javascript Object Freeze Example

The syntax of Javascript Object.freeze() Tutorial is following.

Object.freeze(obj)

The obj argument is the object which needs to freeze.

Let’s see the following example.

// app.js

const student = { name: 'KRUNAL', education: 'BE IT' };
const freezedObj = Object.freeze(student);
freezedObj.name = 'ANKIT';
console.log(freezedObj);

The output is following.

 

Javascript Object Freeze Example

See, after freezing the student object, the property is not changed. We changed it manually, but still, it remains the same object as we have defined.

Freezing an object also prevents its prototype from being changed. The freeze() method returns the same object that was passed in.

Use strict mode

When we can write the above code in the strict mode, it will give an exception. See the following example.

// app.js

'use strict';

const student = { name: 'KRUNAL', education: 'BE IT' };
const freezedObj = Object.freeze(student);
freezedObj.name = 'ANKIT';
console.log(freezedObj);

The output is following.

 

Object.freeze() Tutorial

Nothing can be added to or removed from the properties set of the frozen object. Any attempt to do so will fail, either silently or by throwing the TypeError exception (most commonly, but not exclusively, when in strict mode).

The freeze() method returns the same object that was passed into the function. It does not create the frozen copy. For data properties of the frozen object, values cannot be changed; the writable and configurable attributes are set to false.

Finally, Javascript Object Freeze Example | Object.freeze() Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.