Hey all! π JavaScript ES6 has an awesome feature called destructuring assignment. Let's talk about it π.
Introduction - What is destructuring assignment?
Destructing assignment allow you assign array or object properties to a variable in an easy way. This means that you can write less code in order to unpack (grab things from) arrays and objects and assign it to individual variable. The code can look cleaner and it improves readability.
Array destructuring example:
The properties of the arrays are the index, and the syntax resemble an array literal. You can assign a value within the array corresponding to its position in the array and skip values by leaving a blank space (see example below).
// without destructuring
const days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
const first = days[0];
const TGIF = days[4];
const restDay = days[6]
console.log(first, TGIF, restDay) // "monday" "friday" "sunday"
// with destructuring
const [firstDay, , , , fifthDay, , sunday] = days;
console.log(firstDay, fifthDay, sunday) // "monday" "friday" "sunday"
It is also possible to assign the remaining values using the ...
spread syntax when destructuring. You might commonly see it as ...rest
this basically means to store the remaining elements to the variable called "rest".
const [, secondDay, ...remainDays] = days;
console.log(remainDays) //["wednesday","thursday","friday","saturday","sunday"]
Object destructuring example:
Similar to array destructuring, the syntax of object destructuring resemble the object literal and it allows you to assign the properties of an object to a variable. The left hand-side represents the property/variable names and the right hand-side of the equal sign is the object which you would like to unpack.
If you intend to assign a property to a same name variable, you can simply write { propertyName }
(as seen in example 1 below) or if you wish to rename you can simply write { propertyName: desiredVariableName }
(as seen in example 2 below). You can also use nested destructuring for more complex objects.
// Example 1
const user = {
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org"
}
const { name, email, phone } = user;
console.log(`${name} has email ${email} and reachable on ${phone}`) // "Leanne Graham has email Sincere@april.biz and reachable on 1-770-736-8031 x56442"
// Example 2
const wrestler = {
name: "John Cena",
moves: ["Tornado DDT", "Side Slam", "Five Knuckle Shuffle"]
}
const { name: FullName, moves: [,,bestMove]} = wrestler;
console.log(FullName +" best move is " + bestMove) // "John Cena best move is Five Knuckle Shuffle"
Default values
You can also set a default value for the cases where the property you are trying to extract does not exist (this would typically return undefined).
const [pi = 3.14] = [];
console.log(pi); // 3.14
const { codename = "Twilight" } = { name: "Loid Forger", profession: "Psychiatrist" };
console.log( codename ); // "Twilight"
My recent usage
This is very helpful when you wish to extract only specific property from an object or array. As I work with React, the typically usage for object destructuring is when importing from React library e.g. import React, { useState, useEffect } from 'react'
, destructuring props passed down the components or destructuring objects returned from API calls. I have also recently used array destructuring to easily swap two elements in an array to solve DSA problems:
const grid = ["empty", "fulled"];
[grid[0], grid[1]] = [grid[1], grid[0]];
console.log(grid); // ["fulled","empty"]
// without array destructuring
const newGrid = ["one", "two"];
const temp = newGrid[0];
newGrid[0] = newGrid[1];
newGrid[1] = temp;
console.log(newGrid) // ["two", "one"]
Summary
Destructuring assignment is a useful syntax that allows you to write cleaner code to assign properties of array and objects to individual variables using similar syntax to the array or object literals. Give it a try π.
For more detailed information and example, you can find it here MDN
Thank you for reading, if you have anything to add please let me know.