A Comprehensive Guide to JavaScript Objects - Part 2
A Comprehensive Guide to JavaScript Objects - Part 2
Building on the basics of objects, this part dives into advanced methods, object immutability, inheritance, and performance
considerations. Mastering these concepts will make your JavaScript skills more robust and versatile.
Object.freeze()
The Object.freeze() method freezes an object, making it immutable. You cannot add, remove, or change its properties.
let car = {
make: 'Toyota',
model: 'Corolla'
};
Object.freeze(car);
car.year = 2020; // Cannot add new properties
car.make = 'Honda'; // Cannot modify existing properties
console.log(car);
// Output: {make: 'Toyota', model: 'Corolla'}
Use Cases
Freezing objects is useful when you want to ensure that certain configurations or constants remain unchanged throughout the
program.
Object.seal()
The Object.seal() method prevents adding or removing properties but allows modification of existing properties.
let user = {
name: 'Alice',
age: 25
};
Object.seal(user);
user.age = 26; // Modification allowed
delete user.name; // Cannot delete properties
user.gender = 'Female'; // Cannot add new properties
console.log(user);
// Output: {name: 'Alice', age: 26}
Use Cases
Sealing objects is useful when you want to allow updates but prevent structural changes.
Object.hasOwnProperty()
The hasOwnProperty() method checks if a property belongs to the object directly (not inherited).
Object.getPrototypeOf()
Prototypal Inheritance
In JavaScript, objects can inherit properties and methods from other objects. This is called prototypal inheritance.
Example
let animal = {
eats: true,
walk: function() {
console.log('Animal walks');
}
};
Prototype Chain
When you try to access a property or method, JavaScript first looks at the object itself. If it doesn’t find it, it traverses up the
prototype chain.
Performance Considerations
While objects are efficient for data storage and manipulation, large objects or deep prototype chains can impact performance.
Keep objects shallow to minimize the cost of traversing prototype chains. Use Object.keys() or Object.entries()
instead of loops for better readability and performance.
Destructuring Objects
When copying objects, it’s important to understand the difference between shallow and deep copies.
Shallow Copy
let obj = { a: 1, b: { c: 2 } };
let shallowCopy = Object.assign({}, obj);
shallowCopy.b.c = 3;
console.log(obj.b.c); // Output: 3
Deep Copy
function printNested(obj) {
for (let key in obj) {
if (typeof obj[key] === 'object') {
printNested(obj[key]);
} else {
console.log(key + ': ' + obj[key]);
}
}
}
let company = {
name: 'Tech Corp',
departments: {
engineering: { head: 'Alice', employees: 100 },
marketing: { head: 'Bob', employees: 50 }
}
};
printNested(company);
// Output:
// name: Tech Corp
// head: Alice
// employees: 100
// head: Bob
// employees: 50