Destructuring in JavaScript

Melissa Guachun - Jun 8 '22 - - Dev Community

This is probably going to be a shorter article on a very important and useful concept. In this article, I'll be going over some basic uses of the destructuring assignment in JavaScript!

The destructuring assignment is a special syntax that allows us to extract properties from an object or array. From there, we are able to bind them to variables.

Destructuring is super useful to know once you understand the basics of it's usage. This concept allows you to take data from arrays, objects, and maps and attach them into new and unique variables. We can even extract multiple properties or elements from an array at a time.

Let's look at an example to understand how this concept works:

Instead of writing this:

const inviteList = ["John", "Anna", "Paulina", "Chris"];

const guestOfHonor = inviteList[0];
const guestOne = inviteList[1];
const guestTwo = inviteList[2];
const guestThree = inviteList[3];

Enter fullscreen mode Exit fullscreen mode

We can use destructuring to unpack our values from arrays or objects attach them to variables.


const inviteList = ["John", "Anna", "Paulina", "Chris"];

const [honoredGuest, firstGuest, secondGuest, thirdGuest] = inviteList;


Enter fullscreen mode Exit fullscreen mode

By destructuring, we are able to assign to the honoredGuest (John), firstGuest (Anna), secondGuest (Paulina), and thirdGuest(Chris).


Let's look at an example when working with objects!

const cat = {
name: 'Cleo',
age: 3,
breed: 'Calico'
}

const { name, age, breed } = cat

console.log(name) //Cleo
console.log(age) // 3
console.log(breed) // Calico

Enter fullscreen mode Exit fullscreen mode

Above, we assign separate variables to the name, age, and breed of a cat.


Now let's see how we can change the names of the variables.

const cat = {
name: 'Cleo',
age: 3,
breed: 'Calico'
}

const { name: catName, age: catAge, breed: catBreed } = cat

console.log(catName) //Cleo
console.log(catAge) // 3
console.log(catBreed) // Calico

Enter fullscreen mode Exit fullscreen mode

Let's look a nested example of a destructuring assignment for an array:


const nestedArr = [1, [2,4], [5,7,9]]

const [first, [second, third], fourth] = nestedArr

console.log(first) //1
console.log(second) //2
console.log(third) //4
console.log(fourth) // [5,7,9]

Enter fullscreen mode Exit fullscreen mode

Finally, let's look at destructuring assignment with objects:


let employee = {
id: 1001,
name: {
   firstName: 'John',
   lastName: 'Doe'
   }
};

const {
   name: {
    firstName,
    lastName
    },
 name
} = employee;

console.log(firstName); // John
console.log(lastName); // Doe
console.log(name); //{firstName: 'John', lastName:'Doe'}


Enter fullscreen mode Exit fullscreen mode

This is just the tip of the iceberg as to what destructuring can do!

. . . . . . . . . . . . . . . . . . . . . . .