Careeroza
Destructuring
Array Destructuring
Example
const [first, second, ...rest] = ["HTML", "CSS", "JS", "SQL"];
console.log(first, second, rest);
let a = 1, b = 2;
[a, b] = [b, a]; // swap
console.log(a, b);
const [x = 10, y = 20] = [5];
console.log(x, y);Output
HTML CSS [ 'JS', 'SQL' ] 2 1 5 20
Object Destructuring
Example
const user = { name: "Asha", age: 21, address: { city: "Hyderabad" } };
const { name, age: years, phone = "N/A", address: { city } } = user;
console.log(name, years, phone, city);
function printUser({ name, age }) {
console.log(`${name} is ${age}`);
}
printUser(user);Output
Asha 21 N/A Hyderabad Asha is 21