JavaScript Object freeze() method is used to prevent the modification of an object by making its properties read-only. When an object is frozen using Object.freeze(), its properties become read-only and cannot be changed, added, or removed.
Object.freeze(obj)
JavaScript Object freeze() example
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
const myObject = {
name: 'John',
age: 30
};
Object.freeze(myObject);
myObject.name = 'Jane'; // This will have no effect
console.log(myObject);
</script>
</body>
</html>
Output:
This method can be used to ensure that an object’s values remain consistent throughout the program and that unintended changes do not occur.
Note: This only freezes the object’s immediate properties. If an object property is an object itself, that property’s properties are not automatically frozen. You would have to use Object.freeze()
on the nested object to freeze it completely.
Do comment if you have any doubts or suggestions on this Js object methods topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version