JavaScript Object Methods: Object.keys, values, entries, freeze & seal

The global Object constructor provides specialized static utility methods to inspect, transform, duplicate, and secure objects in production applications.

1. Extracting Properties: Object.keys, values & entries

const book = {
    title: "Mastering Node.js",
    author: "Sandeep Kumar",
    price: 750
};

// 1. Object.keys() -> Array of keys
console.log(Object.keys(book)); // ["title", "author", "price"]

// 2. Object.values() -> Array of values
console.log(Object.values(book)); // ["Mastering Node.js", "Sandeep Kumar", 750]

// 3. Object.entries() -> Array of [key, value] pairs (Perfect for for..of!)
for (const [key, value] of Object.entries(book)) {
    console.log(`${key}: ${value}`);
}

2. Object Immutability: Object.freeze() vs. Object.seal()

Feature Object.seal(obj) Object.freeze(obj)
Add New Properties Forbidden Forbidden
Delete Existing Properties Forbidden Forbidden
Modify Existing Values Allowed Forbidden (Read-only!)
const appConfig = {
    apiUrl: "https://api.veewom.com",
    retryAttempts: 3
};

Object.freeze(appConfig);

// Attempting mutations in strict mode throws TypeError:
// appConfig.retryAttempts = 10; // Fails!
// appConfig.timeout = 5000;     // Fails!
console.log("Is Frozen?", Object.isFrozen(appConfig)); // true

University Exam Corner (BCA / B.Sc CS)

Exam Question: "How do you merge two objects in JavaScript? Compare Object.assign and Object Spread."

const target = { a: 1, b: 2 };
const source = { b: 99, c: 3 };

// Method A: Object.assign (ES5/ES6)
const mergedA = Object.assign({}, target, source); // { a: 1, b: 99, c: 3 }

// Method B: Spread Syntax (Modern Preferred)
const mergedB = { ...target, ...source };          // { a: 1, b: 99, c: 3 }

Next Step

How do you extract values from objects and arrays in a single line? Proceed to: JavaScript Destructuring Assignment: Arrays & Objects →

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!