Destructuring is a convenient way to extract values from arrays or properties from objects into separate variables.
You can assign array values to variables in a single line:
const colors = ["red", "green", "blue"];
const [first, second, third] = colors;
console.log(first); // "red"
console.log(second); // "green"
Extract object properties easily into variables:
const person = { name: "Alice", age: 30 };
const { name, age } = person;
console.log(name); // "Alice"
console.log(age); // 30
If a value is undefined, you can set a default:
const [a = 1, b = 2] = [];
console.log(a); // 1
console.log(b); // 2
let x = 5, y = 10;
[x, y] = [y, x];
console.log(x); // 10
console.log(y); // 5
const user = {
id: 101,
profile: {
name: "John",
age: 25
}
};
const { profile: { name, age } } = user;
console.log(name); // "John"
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!