DEV Community

Jose Aguilar
Jose Aguilar

Posted on • Edited on

The power of destructuring in JavaScript

Hello! My name is Jose and this is my very first DEV post! I am currently a Software Engineering student at Flatiron School, or in other words a newbie. My journey thus far has been quite challenging but rewarding and honestly, also fun!

Perhaps you're a beginner as well and are looking to pick up some a trick or two, well you've found the right place! One of the things I love as I continue to learn JavaScript is coming across cool shorthand techniques that help you achieve your goals with more concise code. In this post I will talking about one of my favorites, destructuring.

What is destructuring?

The MDN defines destructuring assignment as follows:

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Let's explore this with some examples...


Object destructuring

You're probably already familiar with objects and how we can save property values in variables.

Consider the following example:

const employee = {
  firstName: "Peter",
  lastName: "Gibbons",
  jobTitle: "Programmer",
  programmingLanguage: "JavaScript"
};

const firstName = employee.firstName;
const lastName = employee.lastName;
const jobTitle = employee.jobTitle;
const programmingLanguage = employee.programmingLanguage;

console.log(firstName); //LOG: "Peter"
console.log(lastName); //LOG: "Gibbons"
console.log(jobTitle); //LOG: "Programmer"
console.log(programmingLanguage); //LOG: "JavaScript"
Enter fullscreen mode Exit fullscreen mode

This works perfectly fine and achieves what we want to do, but that's a lot of typing... We have to explicitly name each property with the employee object in dot . notation, then declare variables accordingly.

But there's a better way, a way that's more concise and just.. cooler looking.

const employee = {
  firstName: "Peter",
  lastName: "Gibbons",
  jobTitle: "Programmer",
  programmingLanguage: "JavaScript"
};


const { firstName, lastName, jobTitle, programmingLanguage } = employee;


console.log(firstName); //LOG: "Peter"
console.log(lastName); //LOG: "Gibbons"
console.log(jobTitle); //LOG: "Programmer"
console.log(programmingLanguage); //LOG: "JavaScript"
Enter fullscreen mode Exit fullscreen mode

The left side of the expression contains variables that correspond to the properties of the object that we're working with, wrapped in curly braces { }. The right side of the expression is the object itself.

object destructuring diagram

Source: https://www.educative.io/answers/what-is-object-destructuring-in-javascript

Pretty cool isn't it? We're able to define multiple variables each corresponding to an object property, all in one line of code.

Now, imagine a scenario where you wanted to declare a variable in advance without initializing it. What would happen if we tried to use destructuring assignment to assign a property value to our variable without using let or const?

let firstName;

const employee = {
  firstName: "Peter",
  lastName: "Gibbons",
  jobTitle: "Programmer",
  programmingLanguage: "JavaScript"
};

{ firstName } = employee;

console.log(firstName); //Uncaught SyntaxError: expected expression, got '='
Enter fullscreen mode Exit fullscreen mode

The let and const keywords are essential to destructuring assignments. Because neither were used, JavaScript tried to interpret what was within our curly braces { } as a block of code.

In this scenario, the correct syntax would be to encase the destructuring expression in parentheses ( )

({ firstName } = employee)

console.log(firstName) //LOG: "Peter"
Enter fullscreen mode Exit fullscreen mode

Creating aliases

Now, what if we want to define some variables with names of our own choosing? Luckily we can do that:

const employee = {
  firstName: "Peter",
  lastName: "Gibbons",
  jobTitle: "Programmer",
  programmingLanguage: "JavaScript"
};


const { jobTitle: title, programmingLanguage: language } = employee;


console.log(title); //LOG: "Programmer"
console.log(language); //LOG: "JavaScript"
Enter fullscreen mode Exit fullscreen mode

So, as you can see, the syntax is { propertyName: alias }
Note that attempting to access either jobTitle or programmingLanguage would result in an error.

console.log(jobTitle) //Uncaught ReferenceError: jobTitle is not defined
Enter fullscreen mode Exit fullscreen mode

Array destructuring

Destructuring is also possible with arrays, and it makes extracting data from an array much more simple.

Fortunately, unlike destructuring assignments with objects, our variable names do not need to match the name of each item:

const animals = ["dog", "cat", "bird"];
const [animal1, animal2, animal3] = animals;

console.log(animal1); //LOG: "dog"
console.log(animal2); //LOG: "cat"
console.log(animal3); //LOG: "bird"
Enter fullscreen mode Exit fullscreen mode

With array destructuring assignment, we encase our variable(s) in an array literal [ ], each variable maps to the exact position of the array element.

If the number of variables exceed the number of elements in the array, the last variable will simply return undefined.

const animals = ["dog", "cat", "bird"];
const [animal1, animal2, animal3, animal4] = animals;

console.log(animal4) //LOG: undefined
Enter fullscreen mode Exit fullscreen mode

Also unlike object destructuring, with arrays we can declare variables in advance and initialize later, without the need to wrap our assignment in parentheses:

let a, b, c;
const arr = [1, 2, 3];

[a, b, c] = arr

console.log(a) //LOG: 1
console.log(b) //LOG: 2
console.log(c) //LOG: 3
Enter fullscreen mode Exit fullscreen mode

Working with an array returned from a function

Destructuring with an array return value makes syntax more concise:

function returnArray() {
   return [1, 2, 3];
}

let a, b, c;
[a, b, c] = returnArray();

console.log(a) //LOG: 1
console.log(b) //LOG: 2
console.log(c) //LOG: 3
Enter fullscreen mode Exit fullscreen mode

Rest parameters

Instead of having to create a variable for every element in an array, rest parameters allow you to work with arrays with an indefinite number of elements. The syntax is similar to that of the spread operator. The elements that are 'left over' are collected into another array:

let a, b, rest;

[a, b, ...rest] = [10, 20, 30, 40, 50]

console.log(a) //LOG: 10
console.log(b) //LOG: 20
console.log(rest) //LOG: Array [30, 40, 50]
Enter fullscreen mode Exit fullscreen mode

There you have it. Go ahead and use these in your next project; make your code more concise, and your life easier!

Top comments (1)

Collapse
 
ahmad_butt_faa7e5cc876ea7 profile image
Ahmad

loooooove destructing and the spread operator! good article