Advanced Object Concepts in JavaScript
Objects are one of the most important parts of JavaScript. In earlier chapters, you learned the basics: creating objects, accessing properties, updating values, and copying objects.
Now we will go deeper into:
Object methods
Shallow vs deep copy
Computed properties
Optional chaining
Property descriptors
Object.freeze()andObject.seal()thisinside objectsUseful object utilities
These concepts will help you write more powerful and professional JavaScript.
1. Object Methods (Functions Inside Objects)
A function inside an object is called a method.
let user = {
name: "Aman",
greet() {
console.log("Hello, " + this.name);
}
};
user.greet();
Output:
Hello, Aman
this.name refers to the object property.
2. Computed Property Names
You can use variables as keys.
let key = "username";
let user = {
[key]: "Riya"
};
console.log(user.username);
3. Optional Chaining (?.)
Avoids errors when accessing missing properties.
Without optional chaining:
console.log(user.address.city); // error if address is undefined
With optional chaining:
console.log(user?.address?.city);
If address doesn’t exist ? returns undefined instead of an error.
4. Object.freeze() — Make Object Read-Only
let student = {
name: "Aman",
age: 20
};
Object.freeze(student);
student.age = 21; // no effect
console.log(student.age);
Output:
20
freeze() prevents:
Adding properties
Removing properties
Changing values
5. Object.seal() — Allow Modify but Prevent Add/Delete
let emp = { name: "Meera", salary: 40000 };
Object.seal(emp);
emp.salary = 45000; // allowed
emp.age = 25; // not allowed
console.log(emp);
6. Object.keys(), Object.values(), Object.entries()
Object.keys()
Returns all keys in an array.
let user = { name: "Riya", city: "Delhi" };
console.log(Object.keys(user));
Output:
["name", "city"]
Object.values()
console.log(Object.values(user));
Object.entries()
Returns an array of [key, value] pairs.
console.log(Object.entries(user));
7. Merging Objects (Advanced)
Using spread operator
let obj1 = { a: 1 };
let obj2 = { b: 2 };
let merged = { ...obj1, ...obj2 };
console.log(merged);
Using Object.assign()
let final = Object.assign({}, obj1, obj2);
8. Deep Copy vs Shallow Copy (Important)
Shallow Copy (First Level Only)
let person = { name: "Aman", address: { city: "Delhi" } };
let copy = { ...person };
copy.address.city = "Mumbai";
console.log(person.address.city);
Output:
Mumbai (shallow copy shares nested object)
Deep Copy
let deepCopy = JSON.parse(JSON.stringify(person));
deepCopy.address.city = "Kolkata";
console.log(person.address.city); // Delhi
9. Property Descriptors
Every property has hidden settings:
writable
enumerable
configurable
Example:
let user = {};
Object.defineProperty(user, "name", {
value: "Aman",
writable: false
});
user.name = "Riya"; // no effect
console.log(user.name);
Output:
Aman
10. this in Objects (Important)
Inside an object, this refers to the object itself.
let car = {
company: "Honda",
model: "City",
detail() {
console.log(this.company, this.model);
}
};
car.detail();
11. Object Cloning Function (Useful Utility)
function clone(obj) {
return { ...obj };
}
let user1 = { name: "Aman" };
let user2 = clone(user1);
console.log(user2);
Real-Life Example 1: User Profile Updater
let profile = {
name: "Riya",
email: "[email protected]",
address: { city: "Delhi", pin: 110045 }
};
let updated = {
...profile,
address: { ...profile.address, city: "Mumbai" }
};
console.log(updated);
Real-Life Example 2: Settings Manager
let settings = {
theme: "light",
notifications: true
};
Object.freeze(settings);
Example Program (Complete)
let student = {
name: "Aman",
marks: { math: 95, english: 88 },
show() {
console.log(`${this.name} scored ${this.marks.math} in Math`);
}
};
// deep copy
let stud2 = JSON.parse(JSON.stringify(student));
stud2.marks.math = 70;
student.show();
Output:
Aman scored 95 in Math
Common Mistakes Beginners Make
Using shallow copy when deep copy is needed
Confusing
Object.seal()withObject.freeze()Accessing missing properties without optional chaining
Using arrow functions for object methods (incorrect
this)Forgetting to deep clone nested objects
Practice Tasks (Do It Yourself)
Create an object and freeze it. Try modifying it.
Merge two objects using the spread operator.
Deep clone an object using JSON methods.
Use optional chaining on a missing nested property.
Create an object method that uses
thisto print details.