JavaScript(JS) object method - freeze
In JavaScript, the Object.freeze()
method is used to freeze an object, which prevents its properties from being modified. Once an object is frozen, its properties cannot be added, removed, or changed. Any attempt to modify a frozen object or its properties will result in an error or failure silently in strict mode.
The syntax for using Object.freeze()
is as follows:
Object.freeze(obj)
Where obj
is the object to freeze.
Here's an example of using Object.freeze()
:
const person = { name: 'John', age: 30, city: 'New York' }; Object.freeze(person); person.age = 35; // This will not have any effect in a strict mode environment console.log(person.age); // Output: 30
In this example, we create an object called person
with three properties: name
, age
, and city
. We then call Object.freeze()
on the person
object to freeze it. Finally, we try to modify the age
property of person
, but it has no effect, and the value of person.age
remains 30
.
It's important to note that Object.freeze()
only freezes the top-level properties of an object. If the object contains nested objects or arrays, those nested objects or arrays are not frozen and can still be modified.
Also, Object.freeze()
only makes an object read-only and not immutable. If a property of a frozen object is an object or an array, that object or array can still be modified.