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 literalconst user = {id: 1,name: "Ali",age: 25,isAdmin: false,address: { // nested objectcity: "Rawalpindi",country: "Pakistan"},greet() { // method (function as property)return `Hi, I'm ${this.name}`;}};// Accessing propertiesuser.name; // "Ali" — dot notationuser["age"]; // 25 — bracket notation (dynamic keys)user.address.city; // "Rawalpindi" — nested access// Dynamic key accessconst key = "name";user[key]; // "Ali" — variable as key// Modifyinguser.age = 26; // change existinguser.email = "ali@example.com"; // add new propertydelete user.isAdmin; // remove property// Check if property exists"name" in user; // trueuser.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 destructuringconst { name, age } = user;console.log(name); // "Ali"// Rename while destructuringconst { name: fullName, age: years } = user;console.log(fullName); // "Ali"// Default valuesconst { role = "user", theme = "dark" } = user;// role = "admin" (from object), theme = "dark" (default)// Nested destructuringconst { address: { city } = {} } = user; // safe nested// Rest in destructuringconst { name: n, ...rest } = user;// n = "Ali", rest = { age: 25, role: "admin", city: "Rawalpindi" }// Spread to clone/mergeconst updated = { ...user, age: 26 }; // clone + overrideconst merged = { ...user, ...{ theme: "dark" } };// Computed property namesconst field = "username";const dynamic = { [field]: "ali123" }; // { username: "ali123" }// Shorthand when variable name = key nameconst 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