Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

A Comprehensive Guide to JavaScript Objects - Part 2

Uploaded by

xubairacca
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

A Comprehensive Guide to JavaScript Objects - Part 2

Uploaded by

xubairacca
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

11/19/24, 4:40 AM 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.

Advanced Object Methods

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).

file:///home/zub/Desktop/A Comprehensive Guide to JavaScript Objects - Part 2.html 1/4


11/19/24, 4:40 AM A Comprehensive Guide to JavaScript Objects - Part 2

let person = { name: 'John' };


console.log(person.hasOwnProperty('name')); // Output: true
console.log(person.hasOwnProperty('toString')); // Output: false

Object.getPrototypeOf()

The Object.getPrototypeOf() method retrieves the prototype of an object.

let animal = { species: 'Dog' };


let dog = Object.create(animal);
console.log(Object.getPrototypeOf(dog));
// Output: {species: 'Dog'}

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');
}
};

let dog = Object.create(animal);


dog.barks = true;

console.log(dog.eats); // Output: true (inherited from animal)


dog.walk(); // Output: Animal walks
console.log(dog.barks); // Output: true

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.

Optimizing Object Operations

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.

Additional Object Features

Destructuring Objects

Object destructuring allows you to extract properties into variables.


file:///home/zub/Desktop/A Comprehensive Guide to JavaScript Objects - Part 2.html 2/4
11/19/24, 4:40 AM A Comprehensive Guide to JavaScript Objects - Part 2

let user = { name: 'Alice', age: 25 };


let { name, age } = user;
console.log(name); // Output: Alice
console.log(age); // Output: 25

Shallow vs. Deep Copy

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

let deepCopy = JSON.parse(JSON.stringify(obj));


deepCopy.b.c = 4;
console.log(obj.b.c); // Output: 3

Looping Through Nested Objects


When dealing with nested objects, you may need to use recursive functions to loop through all levels.

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

file:///home/zub/Desktop/A Comprehensive Guide to JavaScript Objects - Part 2.html 3/4


11/19/24, 4:40 AM A Comprehensive Guide to JavaScript Objects - Part 2

file:///home/zub/Desktop/A Comprehensive Guide to JavaScript Objects - Part 2.html 4/4

You might also like