DEV Community

Cover image for JavaScript - Destructuring assignment
Tanwa Sripan
Tanwa Sripan

Posted on

JavaScript - Destructuring assignment

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"

Enter fullscreen mode Exit fullscreen mode

It is also possible to assign the remaining values using the ... spread syntax when destructuring. You might commonly see it as 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"]

Enter fullscreen mode Exit fullscreen mode

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": "",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
    "phone": "1-770-736-8031 x56442",
    "website": ""

const { name, email, phone } = user;

console.log(`${name} has email ${email} and reachable on ${phone}`) // "Leanne Graham has email 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"

Enter fullscreen mode Exit fullscreen mode

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"

Enter fullscreen mode Exit fullscreen mode

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"]

Enter fullscreen mode Exit fullscreen mode


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.

Loid Forger rom Spy Family

Top comments (3)

christypatel profile image

A very good update so far. I even don't have a better experience with destructuring assignment writing. But I would like to complete my own assignment at any cost. I would like to get some tips online if possible. I am mostly interested in professional assignments to choose the correct service I want to go straightforward and complete my writing task at any cost.

justtanwa profile image
Tanwa Sripan

Hey, I am sorry but I am not sure what you mean?

chfrom profile image

Very nice writeup! I didn't know you could do all those tricks with Arrays - could definitely see a use for that!