[Tutorial] JavaScript Destructuring

Here’s a quick explanation about how destructuring works in JavaScript. I’m going to use it in some future tutorials, so I’ll point those tutorials at this explanation.

The explanation is written in the comments here:

// to get the values out of the object
const myObj = {
    a: "hello",
    b: "world",
};

// you could do this
const item1 = myObj.a;
const item2 = myObj.b;

// but there is an easier way now: any names that you use in the curly
// braces will be assigned the values of matching keys in the JS object
const { a, b } = myObj;

// `a` and `b` now have the values from the object
console.log(a, "a"); // "hello"
console.log(b, "b"); // "world"

// It works with arrays too
const myArr = [1, 2, 3];

// the old way requires a lot of typing
const val1 = myArr[0];
const val2 = myArr[1];
const val3 = myArr[2];

// the new way assigns each value of the array in one line
const [x, y, z] = myArr;

console.log("x", x); // 1
console.log("y", y); // 2
console.log("z", z); // 3

You can also use destructuring to extract fields from function arguments.

function printReceipt({ quantity, item, priceEach }) {
    console.log(
        `${item}: ${quantity} x $${priceEach} = $${quantity * priceEach}`
    );
}

// the keys on this object match the names that the function expects
const purchaseData = {
    quantity: 3,
    item: "avocado sandwich",
    priceEach: 9,
};

printReceipt(purchaseData);
// prints "avocado sandwich: 3 x $9 = $27"

The page below shows more examples, like how to get nested fields out of objects.

4 Likes