Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to disallow altering of object variables in JavaScript?
JavaScript provides Object.freeze() to make objects immutable, preventing addition, deletion, or modification of properties. This is useful when you need to protect object data from accidental changes.
Syntax
Object.freeze(object)
Basic Example
When an object is frozen, attempts to modify its properties are silently ignored:
const canNotChangeTheFieldValueAfterFreeze = {
value1: 10,
value2: 20
};
Object.freeze(canNotChangeTheFieldValueAfterFreeze);
// Attempt to change property (will be ignored)
canNotChangeTheFieldValueAfterFreeze.value1 = 100;
console.log("After changing the field value1 from 10 to 100 = " + canNotChangeTheFieldValueAfterFreeze.value1);
After changing the field value1 from 10 to 100 = 10
Testing Object Mutability
You can check if an object is frozen using Object.isFrozen():
const normalObject = { name: "John" };
const frozenObject = Object.freeze({ name: "Jane" });
console.log("Normal object is frozen:", Object.isFrozen(normalObject));
console.log("Frozen object is frozen:", Object.isFrozen(frozenObject));
// Try to modify both
normalObject.name = "Bob";
frozenObject.name = "Alice";
console.log("Normal object name:", normalObject.name);
console.log("Frozen object name:", frozenObject.name);
Normal object is frozen: false Frozen object is frozen: true Normal object name: Bob Frozen object name: Jane
Preventing Property Addition and Deletion
const user = Object.freeze({
id: 1,
name: "Alice"
});
// Attempt to add new property
user.email = "alice@example.com";
// Attempt to delete existing property
delete user.name;
console.log("User object:", user);
console.log("Email property:", user.email); // undefined
console.log("Name property:", user.name); // still exists
User object: { id: 1, name: 'Alice' }
Email property: undefined
Name property: Alice
Limitations: Shallow Freezing
Object.freeze() only performs shallow freezing. Nested objects can still be modified:
const company = Object.freeze({
name: "TechCorp",
address: {
city: "New York",
country: "USA"
}
});
// This won't work (frozen)
company.name = "NewCorp";
// This will work (nested object not frozen)
company.address.city = "San Francisco";
console.log("Company name:", company.name);
console.log("Company city:", company.address.city);
Company name: TechCorp Company city: San Francisco
Conclusion
Object.freeze() provides an effective way to make objects immutable at the top level. Remember that it only performs shallow freezing, so nested objects require separate freezing if complete immutability is needed.
Advertisements
