DG
DevGuide
Run Code
Home/JavaScript/Objects & Destructuring
JS JavaScript6 / 7

Objects & Destructuring

📌 WHAT

An object is a collection of key-value pairs that groups related data and functionality. Keys are strings (or symbols), values can be anything.

💡 WHY

Objects model real-world entities. Every API response, React props, component state, and database row is an object. Mastering objects is essential.

⏰ WHEN / WHERE

Constantly. config objects, API response parsing, component props, function parameters that accept options, state management.

🔧 HOW

Create with {} syntax. Access with dot notation (obj.key) or bracket notation (obj['key']). Destructure to extract values into variables cleanly.

Code Examples

#1Objects: creation, access, methods

Objects: creation, access, methods
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Object literal
const user = {
id: 1,
name: "Ali",
age: 25,
isAdmin: false,
address: { // nested object
city: "Rawalpindi",
country: "Pakistan"
},
greet() { // method (function as property)
return `Hi, I'm ${this.name}`;
}
};
// Accessing properties
user.name; // "Ali" — dot notation
user["age"]; // 25 — bracket notation (dynamic keys)
user.address.city; // "Rawalpindi" — nested access
// Dynamic key access
const key = "name";
user[key]; // "Ali" — variable as key
// Modifying
user.age = 26; // change existing
user.email = "ali@example.com"; // add new property
delete user.isAdmin; // remove property
// Check if property exists
"name" in user; // true
user.hasOwnProperty("age"); // true

#2Destructuring, spread, computed keys

Destructuring, spread, computed keys
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const user = { name: "Ali", age: 25, role: "admin", city: "Rawalpindi" };
// Basic destructuring
const { name, age } = user;
console.log(name); // "Ali"
// Rename while destructuring
const { name: fullName, age: years } = user;
console.log(fullName); // "Ali"
// Default values
const { role = "user", theme = "dark" } = user;
// role = "admin" (from object), theme = "dark" (default)
// Nested destructuring
const { address: { city } = {} } = user; // safe nested
// Rest in destructuring
const { name: n, ...rest } = user;
// n = "Ali", rest = { age: 25, role: "admin", city: "Rawalpindi" }
// Spread to clone/merge
const updated = { ...user, age: 26 }; // clone + override
const merged = { ...user, ...{ theme: "dark" } };
// Computed property names
const field = "username";
const dynamic = { [field]: "ali123" }; // { username: "ali123" }
// Shorthand when variable name = key name
const name2 = "Ali";
const age2 = 25;
const person = { name2, age2 }; // same as { name2: name2, age2: age2 }

Practice This Concept

Open the playground, paste any example, and experiment. The best way to learn is by breaking things.

Open in Playground