Lesson 76 – JavaScript Destructuring Assignment (Arrays & Objects)
Destructuring is a concise way to extract values from arrays or properties from objects into distinct variables. It makes code cleaner and more readable.
Destructuring Arrays
const numbers = [1, 2, 3];
// Traditional way
const first = numbers[0];
const second = numbers[1];
// Destructuring
const [a, b] = numbers;
console.log(a); // 1
console.log(b); // 2
You can also skip elements:
const [x, , z] = [10, 20, 30];
console.log(z); // 30
Use default values:
const [p = 100, q = 200] = [50];
console.log(p); // 50
console.log(q); // 200
Destructuring Objects
const person = {
name: "Jane",
age: 25,
country: "Ghana"
};
const { name, age } = person;
console.log(name); // Jane
console.log(age); // 25
Rename variables while destructuring:
const { name: fullName, age: years } = person;
console.log(fullName); // Jane
console.log(years); // 25
Provide default values:
const { gender = "Not specified" } = person;
console.log(gender); // Not specified
Nested Destructuring
const user = {
id: 1,
profile: {
username: "devahmed",
email: "ahmed@example.com"
}
};
const {
profile: { username, email }
} = user;
console.log(username); // devahmed
Try Your Hand
-
Destructure this array and get the first and last item:
const colors = ["red", "green", "blue", "yellow"];
-
Destructure the object and rename the keys:
const settings = { resolution: "1080p", fullscreen: true };
Summary
- Destructuring makes it easy to assign variables from arrays or objects.
- Works great with function parameters and default values.
- Helps reduce boilerplate code and improves readability.