destructuring = extract values form arrays and objects, then assign them to variables in a convenient way
[] = to perform array destructuring
{} = to perform object destructuring
Example 1: swap the value of two variables
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a);Example 2: swap elements in an array
const colors = ["red", "green", "blue", " black", "white"];
[colors[0], colors[4]] = [colors[4], colors[0]];
console.log(colors);
//output" 0:"white" 1:"green" 2:"blue" 3:" black" 4:"red"Example 3: assign array elements to variables
const colors = ["red", "green", "blue", " black", "white"];
const [firstColor, secondColor, thirdColor, ...extraColors] = colors;
console.log(firstColor);//red
console.log(secondColor);//green
console.log(thirdColor);//blue
console.log(extraColors);//(2) [" black", "white"]Example 4: extract values from objects
const person1 = {
firstName: "spongebob",
lastName: "squarepants",
age: 30,
job: "Fry cook",
}
const person2 = {
firstName: "patrik",
lastName: "star",
age: 34,
}
const {firstName, lastName, age, job="unemployed"} = person2;
console.log(firstName);//patrik
console.log(lastName);//star
console.log(age);//34
console.log(job);//unemployedExample 5: Destructure in function parameters
function displayPerson({firstName, lastName, age, job="unemployd"}){
console.log(`name:${firstName}-${lastName} , ${age}age , work:${job}`)
}
const person1 = {
firstName: "spongebob",
lastName: "squarepants",
age: 30,
job: "Fry cook",
}
const person2 = {
firstName: "patrik",
lastName: "star",
age: 34,
}
displayPerson(person1)
//name:spongebob-squarepants , 30age , work:Fry cook
displayPerson(person2)
//name:patrik-star , 34age , work:unemployd