JavaScript objects are like clay - they can be shaped, protected, and copied in ways you might not expect. Let's break down the magic!
Protecting Your Objects: Freeze vs Seal
Object.freeze() π§
const frozenObject = { name: "Elsa" };
Object.freeze(frozenObject);
frozenObject.name = "Anna"; // Nope!
console.log(frozenObject.name); // Still "Elsa"
Object.seal() π‘οΈ
const sealedObject = { name: "Jack" };
Object.seal(sealedObject);
sealedObject.name = "New Name"; // Works
sealedObject.age = 30; // Blocked!
Key Difference:
-
freeze()
: Prevents ALL changes -
seal()
: Allows value modifications, blocks new properties
Cloning: Shallow vs Deep
Shallow Clone
const original = {
user: { name: "Alice" },
age: 30
};
const shallowCopy = { ...original };
shallowCopy.user.name = "Bob";
console.log(original.user.name); // "Bob" (!) - nested objects still linked
Deep Clone
const deepCopy = JSON.parse(JSON.stringify(original));
// Now changes to nested objects won't affect the original
Immutability Patterns
// Immutable update
const updateUser = (user, updates) => ({
...user,
...updates
});
const alice = { name: "Alice", age: 30 };
const updatedAlice = updateUser(alice, { age: 31 });
Quick Tips
- Use
freeze()
for constants - Deep clone with
JSON.parse(JSON.stringify())
- Spread operator for non-nested immutable updates
- Consider libraries like Immer for complex immutability
Immutability isn't just a technique - it's a mindset. Protect your data, keep your code predictable! π
Have a mind-bending object manipulation story? Drop it in the comments! π
Liked this deep dive? Follow for more JavaScript insights!
Top comments (1)
object.seal and object.seal. Thanks for the knowledge