DEV Community

Marvin Roque
Marvin Roque

Posted on

JavaScript Object Manipulation: Your Survival Guide

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"
Enter fullscreen mode Exit fullscreen mode

Object.seal() πŸ›‘οΈ

const sealedObject = { name: "Jack" };
Object.seal(sealedObject);

sealedObject.name = "New Name"; // Works
sealedObject.age = 30; // Blocked!
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Deep Clone

const deepCopy = JSON.parse(JSON.stringify(original));
// Now changes to nested objects won't affect the original
Enter fullscreen mode Exit fullscreen mode

Immutability Patterns

// Immutable update
const updateUser = (user, updates) => ({
    ...user,
    ...updates
});

const alice = { name: "Alice", age: 30 };
const updatedAlice = updateUser(alice, { age: 31 });
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
agunechemba profile image
Agunechemba Ekene

object.seal and object.seal. Thanks for the knowledge