DEV Community

Marvin Roque
Marvin Roque

Posted on

1

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!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
agunechemba profile image
Agunechemba Ekene

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more