Objects store data as key–value pairs. They’re the main building block for complex data in JavaScript.
JavaScript Objects
1) Object Literal & Property Access
Create an object with {}. Access with dot or bracket notation.
const user = {
name: 'Sonu',
age: 20,
city: 'Delhi'
};
console.log(user.name); // Sonu
console.log(user['city']); // Delhi
2) Update, Add & Delete Properties
Objects are mutable: change values, add new keys, or remove keys.
user.age = 21; // update
user.country = 'India'; // add
delete user.city; // delete
3) Methods & this
Functions stored on objects are methods. Inside a method, this refers to the object.
user.greet = function() {
return `Hello, I'm ${this.name}`;
};
console.log(user.greet()); // Hello, I'm Sonu
4) Nested Objects & Optional Chaining
Use ?. to safely access deep properties that might be missing.
const order = {
id: 101,
customer: { name: 'Asha' }
};
const nick = order.customer?.nickname ?? 'Guest';
// "Guest" (because nickname is undefined)
5) Iterating Keys & Values
Loop properties with for...in, or get arrays of keys/values/entries.
// for...in (keys)
for (let k in user) {
console.log(k, user[k]);
}
// keys, values, entries
const keys = Object.keys(user);
const vals = Object.values(user);
const pairs = Object.entries(user);
6) Destructuring
Extract properties into variables quickly.
const { name, age } = user;
console.log(name, age);
7) Spread & Object.assign
Clone or merge objects (shallow copy).
const a = { x: 1, y: 2 };
const b = { y: 9, z: 3 };
const copy1 = { ...a }; // spread copy
const merged = { ...a, ...b }; // merge
const copy2 = Object.assign({}, a); // assign copy
8) JSON: stringify & parse
Convert objects to JSON (text) and back.
const json = JSON.stringify(user);
const obj = JSON.parse(json);
Tip: Spread/assign do a shallow copy. For deep clones, you can use
structuredClone(obj) (modern browsers) or libraries.