Home » Posts » Destructuring Assignment

Destructuring Assignment

Destructuring assignment is a JavaScript feature which allows assignment of values from array and properties from object to distinct variables.

Examples

Swapping two numbers

    let a = 10, b = 20;
    console.log(`a = ${a} and b = ${b}`);
    [a, b] = [b, a];
    console.log(`a = ${a} and b = ${b}`);
a = 10 and b = 20
a = 20 and b = 10

Variable assignment

    const colors = ['#ff0000', "#00FF00", "#0000FF"];
    const [red, green, blue] = colors;
    console.log(red, green, blue);
#ff0000 #00FF00 #0000FF
    const pc = {
        ram: 32,
        cpu: 'ryzen 5000',
        gpu: 'rtx 3080',
    };
    const { ram, gpu } = pc;
    console.log(ram, gpu);
32 rtx 3080

Assigning default values

    let [burger = 3.5, fries = 1.45] = [4.2];
    console.log(`Today's rate - Burger $${burger} and Fries $${fries}`);
Today's rate - Burger $4.2 and Fries $1.45
    const { primaryPower = 'flight', secondaryPower = 'strength' } = { secondaryPower: 'invisibility' };
    console.log(primaryPower, secondaryPower);
flight invisibility

Assigning remaining values

    const numbers = [1, 2, 3, 4, 5];
    const [one, ...otherThenOne] = numbers;
    console.log(one, otherThenOne);
1 [ 2, 3, 4, 5 ]

New variable name

    const { origVar: newVar } = { origVar: 'What are you looking at?' }
    console.log(newVar);
What are you looking at?

References

  1. Mozilla Developer Network (MDN)

Leave a Reply

Your email address will not be published.