Skip to main content

Command Palette

Search for a command to run...

✨ Essential JavaScript Object Methods Explained with Examples ✨

JavaScript Objects: Methods, Immutability, Copying & Destructuring Simplified.

Published
•8 min read•View as Markdown
✨ Essential JavaScript Object Methods Explained with Examples ✨

Objects are the building blocks of JavaScript, and mastering their manipulation is key to writing clean, efficient code. Let’s dive into core object methods, immutability techniques, copying strategies, and more—with practical examples!


🔑 Core Object Methods

📦 Example Object

const product = {
    name: 'iPhone 14 Pro',
    company: 'Apple',
    price: 125000,
    warranty: '1 Year',
    color: 'Black',
};

1️⃣ Object.keys() → Get All Keys

Returns an array of an object’s property names.

Object.keys(product);
// Output: ['name', 'company', 'price', 'warranty', 'color']

2️⃣ Object.values() → Get All Values

Returns an array of an object’s property values.

Object.values(product);
// Output: ['iPhone 14 Pro', 'Apple', 125000, '1 Year', 'Black']

3️⃣ Object.entries() → Get Key-Value Pairs

Returns an array of [key, value] pairs.

Object.entries(product);
// Output: [ ['name', 'iPhone 14 Pro'], ['company', 'Apple'], ... ]

4️⃣ Object.hasOwn() → Check Property Existence (Modern Alternative to hasOwnProperty)

Checks if an object has a specific property.

Object.hasOwn(product, 'price'); // true ✅  
Object.hasOwn(product, 'discount'); // false ❌

5️⃣ Counting Properties

Object.keys(product).length; // 5

🔒 Object Immutability in JavaScript

❗ Why const Does Not Make Objects Immutable

In JavaScript, when you use const to declare an object, it only prevents reassignment of the variable binding, not the contents of the object.

This behavior can be better understood by looking at how JavaScript memory works:

  • Stack Memory stores primitive values and variable references.

  • Heap Memory stores objects and non-primitive data.

const product = {name: 'Laptop', price: 120000};
  • Here, the product variable (a reference) is stored on the stack.

  • The actual object { name: "Laptop", price: 120000 } lives in the heap.

  • const only makes the stack reference immutable (i.e., you can’t do product = {}), but the heap object can still be modified (i.e., product.price = 99999 is allowed).

✅ Example:

const product = {name: 'Laptop', price: 120000};
product.price = 99999; // ✅ Allowed
product = {}; // ❌ TypeError: Assignment to constant variable.

So, to make an object truly immutable, you need to prevent changes to the object in the heap, not just restrict the reference.


✅ Making Objects Immutable with Built-in Methods

JavaScript provides three methods to control how much an object can be modified in the heap:

1️⃣ Object.preventExtensions()

  • Prevents adding new properties.

  • Allows modifying and deleting existing properties.

const product = {name: 'Laptop', price: 120000};
Object.preventExtensions(product);

product.stock = 100; // ❌ Fails silently (not added)
product.price = 99999; // ✅ Allowed
delete product.name; // ✅ Allowed

2️⃣ Object.seal()

  • Prevents adding or deleting properties.

  • Allows modifying existing properties.

const product = {name: 'Laptop', price: 120000};
Object.seal(product);

delete product.price; // ❌ Fails silently
product.price = 150000; // ✅ Allowed
product.brand = 'Dell'; // ❌ Fails silently

3️⃣ Object.freeze()

  • Prevents adding, deleting, and modifying properties.

  • Makes the object completely immutable (shallow freeze).

const product = {name: 'Laptop', price: 120000};
Object.freeze(product);

product.price = 90000; // ❌ Ignored silently
delete product.name; // ❌ Ignored silently
product.stock = 10; // ❌ Ignored silently

⚠️ Note: Object.freeze() is shallow—nested objects inside are still mutable unless you recursively freeze them.

📊 Quick Comparison

MethodAdd PropertiesDelete PropertiesModify Properties
Object.preventExtensions()❌ No✅ Yes✅ Yes
Object.seal()❌ No❌ No✅ Yes
Object.freeze()❌ No❌ No❌ No

🔍 Checking Object Mutability Status

You can check the status of any object using the following built-in methods:

Object.isExtensible(product); // false if preventExtensions or sealed or frozen
Object.isSealed(product); // true if sealed or frozen
Object.isFrozen(product); // true only if frozen

🔧 Advanced Object Control

For fine-tuned control over object properties, JavaScript offers Object.defineProperty(). This lets you set attributes like:

  • writable – Can the value be changed?

  • configurable – Can the property be deleted or reconfigured?

  • enumerable – Will the property show up in loops like for...in?

✅ Example:

Object.defineProperty(product, 'price', {
    writable: false,       // Cannot change value
    configurable: false,   // Cannot delete or redefine
});

product.price = 1; // ❌ Fails silently (no error)
delete product.price; // ❌ Also fails

🛠️ Polyfills for Object.seal() and Object.freeze()

If you're working in an older environment without native support, you can mimic the behavior using custom polyfills.

🔹 Polyfill for Object.seal()

Object.customSeal = function (obj) {
    Object.keys(obj).forEach(key => {
        Object.defineProperty(obj, key, {configurable: false});
    });
    return Object.preventExtensions(obj);
};

🔹 Polyfill for Object.freeze()

Object.customFreeze = function (obj) {
    Object.keys(obj).forEach(key => {
        Object.defineProperty(obj, key, {
            writable: false,
            configurable: false,
        });
    });
    return Object.preventExtensions(obj);
};

📝 Copying Objects: Shallow vs Deep

When copying objects in JavaScript, it's important to understand whether you're creating a shallow copy or a deep copy.

1️⃣ Shallow Copy

A shallow copy only copies the top-level properties. If the object contains nested objects, those are still * *shared (referenced)**.

✅ Methods:

const copy1 = Object.assign({}, product);
const copy2 = {...product};

⚠️ Problem Example:

const original = {a: 1, nested: {b: 2}};
const shallowCopy = {...original};
shallowCopy.nested.b = 99;

console.log(original.nested.b); // 99 → Original modified!

2️⃣ Deep Copy

A deep copy creates a fully independent clone, including all nested objects.

✅ Using structuredClone():

const deepCopy = structuredClone(original);
deepCopy.nested.b = 99;

console.log(original.nested.b); // 2 → Original unchanged

🧠 Use deep copy when you want complete independence between the original and copied object.

Here is your updated version with ✅ emojis removed and replaced with 1️⃣ to 7️⃣, as requested. No other changes were made (np = no change):


🎯 Destructuring of Object & Spread Syntax

JavaScript provides powerful syntax enhancements like destructuring and the spread operator, which help write cleaner, more expressive code when working with arrays and objects.

🔹 Destructuring

Destructuring is a concise way to unpack values from arrays or extract properties from objects into individual variables. It makes your code more readable and less verbose.

1️⃣ Basic Object Destructuring

Extract values directly from an object:

const product = {
    name: 'iPhone 14 Pro',
    company: 'Apple',
    price: 125000,
};

const {name, price} = product;

console.log(name); // 'iPhone 14 Pro'
console.log(price); // 125000

2️⃣ Default Values in Destructuring

If the property doesn't exist, you can assign a default value to avoid undefined:

const product = {
    name: 'iPhone 14 Pro',
    price: 125000,
};

const {discount = 0} = product;

console.log(discount); // 0

3️⃣ Destructuring with Derived Values

You can reference existing values inside the same destructuring statement:

const product = {
    name: 'iPhone 14 Pro',
    features: ['5G', 'OLED Display', 'Triple Camera'],
};

const {features, numberOfFeatures = features.length} = product;

console.log(numberOfFeatures); // 3

4️⃣ Aliasing (Renaming Variables During Destructuring)

Use aliases when you want local variable names to differ from object property names:

const product = {
    name: 'iPhone 14 Pro',
    color: 'Black',
};

const {name: productName, color: productColor} = product;

console.log(productName); // 'iPhone 14 Pro'
console.log(productColor); // 'Black'
console.log(name); // ❌ ReferenceError

The original property (name) is not defined as a variable; only the alias is available.

5️⃣ Nested Object Destructuring

Extract properties from nested objects directly:

const product = {
    name: 'iPhone 14 Pro',
    details: {
        color: 'Black',
        releaseYear: 2022,
    },
};

const {
    details: {color, releaseYear},
} = product;

console.log(color); // 'Black'
console.log(releaseYear); // 2022
console.log(details); // ❌ ReferenceError

Only inner values (color, releaseYear) are available; the intermediate details object is not.

6️⃣ Destructuring in Function Parameters

You can destructure parameters directly in function definitions:

function printProduct({name, price, color = 'Unknown'}) {
    console.log(`Name: ${name}`);
    console.log(`Price: ${price}`);
    console.log(`Color: ${color}`);
}

const product = {
    name: 'iPhone 14 Pro',
    price: 125000,
    color: 'Black',
};

printProduct(product);

Perfect for functions that require only specific object properties.

7️⃣ Destructuring a Function's Return Value

If a function returns an object, destructure it immediately upon receiving:

function getProductInfo() {
    return {
        name: 'iPhone 14 Pro',
        price: 125000,
        color: 'Black',
    };
}

const {name, price, color} = getProductInfo();

console.log(name); // 'iPhone 14 Pro'
console.log(price); // 125000
console.log(color); // 'Black'

Clean and efficient way to handle multiple return values.

🔸 Spread Syntax (...)

The spread operator (...) allows you to expand or copy iterable values like arrays or object properties into another object or array.

Merging or Cloning Objects

You can create a shallow copy or override properties during merging:

const product = {
    name: 'iPhone 14 Pro',
    price: 125000,
};

const updatedProduct = {
    ...product,
    price: 130000, // Overrides the price
};

console.log(updatedProduct);
// { name: 'iPhone 14 Pro', price: 130000 }

This does not mutate the original object. Useful for immutability and state updates (e.g., in React apps).


The Bottom Line 🎀

JavaScript objects are powerful, but mastering their methods ensures:

✔️ Efficient data handling (keys, values, entries)
✔️ Controlled immutability (freeze, seal)
✔️ Safe copying (structuredClone)
✔️ Cleaner code (destructuring, spread)

Now you’re ready to use objects like a pro! Keep practicing, and soon it’ll feel easy.

Thanks for reading! If this helped you, share it with a friend. Got questions? Ask below!

See you in the next post—keep coding and having fun! 😃