Javascript Destructuring Assignment

Summary: in this tutorial, you will learn how to use ES6 destructuring feature that allows you to destructure an object or an array into individual variables.

ES6 provides a new feature called destructing assignment that allows you to take an object or an array and destructure it into individual variables. The destructuring assignment does not just help you save some typing but also change the way you structure your code.

Let’s start with the array destructuring.

Array destructuring

Assuming that you have an array of numbers as follows.

To assign variables the elements of an array, you use the following syntax.

The variable x, y and z will take the value of the first, second, and third element of the scores array. The fourth element of the scores array is discarded.

Array destructuring and rest operator

It’s possible to take all remaining elements of an array and put them in a new array by using the rest operator Here is an example.

The a and b variables receive values of the first two elements of the array. And the variable receives all the remaining arguments, which are the last two elements of the scores array.

Assignments

It’s possible to destructure an array in the assignment that separates from the variable’s declaration. See the following example.

Default values

If the value taken from the array is undefined, you can assign the variable a default value.

Swapping variables

The array destructuring makes it easily to swap values of variables without using a temporary variable. See the following example.

Parsing returned array from a function

A function may return an array of values. The array destructuring make it more intuitive to parse the returned array from a function.

Consider the following example.

In this example, the function returns an array of three elements. We used the array destructuring to destructure the array elements into the individual variables a, b, and c in a single line of code.

Of course, you can use the array destructuring to ignore some of the returned values. Suppose, you only interested in the first and the third elements returned from the function, you can ignore the second element of the array as follows:

Object destructuring

Suppose you have an object person with two properties: firstName and lastName.

When you destructure an object, the variable names must match the property names in the object. If the variable name does not match, it receives a value of .

The following example assigns the and variables the values of the and property of the object.

In this example, we declare and assign the variables in the same statement.

Also, you can use the object destructuring in the assignment statement, however, it must be surrounded by parentheses. See the following example.

If you don’t use the parentheses, JavaScript engine interprets the left-hand side as a block. Hence, you would get an error.

Nested object and object destructuring

Assuming that you have an object which has a object as the property.

The following statement destructures the property into individual variables.

In this tutorial, you have learned how to use ES6 destructuring feature to destructure an array or an object into individual variables.

  • Was this tutorial helpful ?
  • Yes   No
varscores=[70,80,90,100];
let[a,b,...args]=scores;
console.log(args);// [90, 100]
    return[10,20,30];
let[a,b,c]=returnArray();
[a,,c]=returnArray();
    firstName:'John',
    lastName:'Doe'
let{firstName,lastName}=person;
console.log(firstName);// John
console.log(lastName);// Doe
({firstName,lastName})=person;
    id:1001,
    profile:{
        firstName:'John',
        lastName:'Doe'
    }
let{profile:{firstName,lastName}}=employee;
console.log(firstName);// John
console.log(lastName);  // Doe

This article warns about going overboard with ES6 language features. Then we’ll start off the series by discussing about Destructuring in ES6, and when it’s most useful, as well as some of its gotchas and caveats.

A word of caution

When uncertain, chances are . By this I don’t mean that using ES6 syntax is a bad idea – quite the opposite, see I’m writing an article about ES6! My concern lies with the fact that when we adopt ES6 features we must do it because they’ll absolutely improve our code quality, and not just because of the “cool factor” – whatever that may be.

The approach I’ve been taking thus far is to write things in plain ES5, and then adding ES6 sugar on top where it’d genuinely improve my code. I presume over time I’ll be able to more quickly identify scenarios where a ES6 feature may be worth using over ES5, but when getting started it might be a good idea not to go overboard too soon. Instead, carefully analyze what would fit your code best first, and be mindful of adopting ES6.

This way, you’ll learn to use the new features in your favor, rather than just learning the syntax.

Onto the cool stuff now!

Destructuring

This is easily one of the features I’ve been using the most. It’s also one of the simplest. It binds properties to as many variables as you need and it works with both Arrays and Objects.

It makes it very quick to pull out a specific property from an object. You’re also allowed to map properties into aliases as well.

You can also pull properties as deep as you want, and you could also alias those deep bindings.

By default, properties that aren’t found will be , just like when accessing properties on an object with the dot or bracket notation.

If you’re trying to access a deeply nested property of a parent that doesn’t exist, then you’ll get an exception, though.

That makes a lot of sense, if you think of destructuring as sugar for ES5 like the code below.

A cool property of destructuring is that it allows you to swap variables without the need for the infamous variable.

Another convenient aspect of destructuring is the ability to pull keys using computed property names.

In ES5, that’d take an extra statement and variable allocation on your behalf.

You can also define default values, for the case where the pulled property evaluates to .

Destructuring works for Arrays as well, as we mentioned earlier. Note how I’m using square brackets in the destructuring side of the declaration now.

Here, again, we can use the default values and follow the same rules.

When it comes to Arrays you can conveniently skip over elements that you don’t care about.

You can also use destructuring in a 's parameter list.

That’s roughly how you can use destructuring. What is destructuring good for?

Use Cases for Destructuring

There are many situations where destructuring comes in handy. Here’s some of the most common ones. Whenever you have a method that returns an object, destructuring makes it much terser to interact with.

A similar use case but in the opposite direction is being able to define default options when you have a method with a bunch of options that need default values. This is particularly interesting as an alternative to named parameters in other languages like Python and C#.

If you wanted to make the options object entirely optional you could change the syntax to the following.

A great fit for destructuring are things like regular expressions, where you would just love to name parameters without having to resort to index numbers. Here’s an example parsing a URL with a random I got on StackOverflow.

Special Case: Statements

Even though statements don’t follow destructuring rules, they behave a bit similarly. This is probably the “destructuring-like” use case I find myself using the most, even though it’s not actually destructuring. Whenever you’re writing module statements, you can pull just what you need from a module’s public API. An example using :

Note that, however, statements have a different syntax. When compared against destructuring, none of the following statements will work.

  • Use defaults values such as
  • “Deep” destructuring style like
  • Aliasing syntax

The main reason for these limitations is that the statement brings in a binding, and not a reference or a value. This is an important differentiation that we’ll explore more in depth in a future article about ES6 modules.

I’ll keep posting about ES6 & ES7 features every day, so make sure to subscribe if you want to know more!

How about we visit string interpolation tomorrow?
We’ll leave arrow functions for monday!

0 thoughts on “Javascript Destructuring Assignment

Leave a Reply

Your email address will not be published. Required fields are marked *