JavaScript Object.freeze: The Complete Guide

0
43
Javascript Object Freeze Example | Object.freeze() Tutorial

Freezing a JavaScript Object does not allow new properties to be added to an Object and prevents removing or altering the existing properties.

JavaScript Object.freeze

JavaScript Object.freeze() is a built-in method that freezes the Object. The frozen Object can no longer be changed. The freezing of an object prevents new properties from being added to it, existing properties from being removed, prevent changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed.

Syntax

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

Object.freeze(obj)

Parameters

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 the following.

JavaScript Object.freeze

See, after freezing the student object, the property is not changed. We changed it manually, but it remains the same Object 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 the following.

Object.freeze() Tutorial

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

The freeze() method returns the same Object passed into the function.

It does not create a frozen copy. Values cannot be changed for data properties of the frozen Object; the writable and configurable attributes are set to false.

That’s it for this tutorial.

Related posts

Javascript Object.keys()

Javascript Object.values()

Javascript Object.assign()

Javascript Object.create()

Leave A Reply

Please enter your comment!
Please enter your name here

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