Object.freeze() method - JavaScript Tutorial

Object.freeze() method

BLUF: This tutorial on Object.freeze() method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: Object.freeze() method

Understanding Object.freeze() method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

The Object.freeze function is utilized to freeze an object, thereby disallowing the addition of new properties to it. This method also restricts any alterations to the current properties, attributes, and their respective values.

Syntax:

Example

Object.freeze(obj)

Parameter

Obj : The object to freeze.

Return value:

This function delivers the object that was provided as an argument.

Browser Support:

Chrome 45.0
Edge 12.0
Firefox 32.0
Opera No

Example 1

Example

const object1 = {
  property1: 22
};
const object2 = Object.freeze(object1);
object2.property1 = 33;
// Throws an error in strict mode
console.log(object2.property1);

Output:

Example 2

Example

const obj1 = { property1: 'freeze'};
const obj2 = Object.freeze(obj1);
obj2.property1 = 'new_data';
  console.log(obj2.property1);

Output:

Output

" freeze "

Example 3

Example

var obj = { prop: function() {}, name: 'charry' };
        console.log(obj);
        obj.name = 'karri';
        delete obj.prop;
        console.log(obj);
        var o = Object.freeze(obj);
        obj.name = 'chris';
        console.log(obj);

Output:

Output

[object Object] {
 name: "charry",
  prop: function() {}
}
[object Object] {
 name: "karri"
}
[object Object] {
 name: "karri"
}

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience