Getting Started with Modern JavaScript — Destructuring

Post Editor

In this article, we go through the syntax of destructuring both Object and Array and give examples of when you can use them.

2 min read
post

Getting Started with Modern JavaScript — Destructuring

In this article, we go through the syntax of destructuring both Object and Array and give examples of when you can use them.

post
post
2 min read
2 min read

The two most used data structures in JavaScript are Object and Array. The destructuring assignment introduced in ECMAScript 2015 is shorthand syntax that allows us to extract array values or object properties into variables. In this article, we go through the syntax of both data structures and give examples of when you can use them.

Destructuring Arrays

In ES5 you could access items in an array by index:

var fruit = ['apple', 'banana', 'kiwi'];

var apple = fruit[0];
var banana = fruit[1];
var kiwi = fruit[2];

With ES6 destructuring, the code becomes simpler:

const [apple, banana, kiwi] = fruit;

Sometimes you might want to skip over items in the array being destructured:

const [,,kiwi] = ['apple', 'banana', 'kiwi'];

Or you can save the other items in an array with the rest pattern:

const [apple, …rest] = ['apple', 'banana', 'kiwi'];

console.log(rest); // -> ['banana', 'kiwi']
Note that the destructuring assignment pattern works for any iterable.

Destructuring Objects

Object destructuring lets you extract properties from objects and bind them to variables. Instead of accessing width through rectangle.width we can access the property and assign it to a variable:

const rectangle = { width: 5, height: 8 };

const { width } = rectangle;

What’s even better, object destructuring can extract multiple properties in one statement. This makes the code clearer. The order of the properties does not matter.

const { width, height } = rectangle;

If we want to change the name of the property we can do it using a colon:

const { width: w, height: h } = rectangle;

console.log(w); // -> 5

Here we assign the property width from rectangle to a variable named w.

Default Values

When you destructure on properties that are not defined, you get undefined:

const { password } = {};

console.log(password); // -> undefined

You can provide default values for when the property you are destructuring is not defined:

const [favorite = 'apple'] = [];
console.log(favorite); // -> apple

const { width = 100 } = {};
console.log(width); // -> 100

Examples

There are many places where we can use destructuring to make the code terser. Let’s see some examples!

String Manipulation

We could for example do some string manipulation on a name and directly assign to variables firstName and lastName:

const [firstName, lastName] = 'Max Best'.split(' ');

// firstName = 'Max', lastName = 'Best'

Swapping Variable Values

Let’s first do the ES5 swap:

var me = 'happy', you = 'sad';

var temp = me;
me = you;
you = temp;

// me = 'sad', you = 'happy'

And now let’s swap back with ES6 destructuring:

[me, you] = [you, me];

// me = 'happy', you = 'sad'

No more need for temporary variables!

Function Parameter Objects

When you are passing multiple parameters it often makes sense to do it as an object. We can use destructuring whenever we want to unpack its properties:

function calculateArea({ width, height }) {
  console.log('Area is ' + width * height);
}

calculateArea({ width: 5, height: 6 }); 
// -> Area is 30

We can also set default values and change variable names:

function calculateArea({ width: w = 10, height: h = 5 }) {
  console.log('Area is ' + w * h);
}

calculateArea({ height: 6 });
// -> Area is 60

Multiple Return Values

If you need to return multiple values from a function, you can return an array or object and destructure the result:

function returnWidthAndHeight() {
  return [5, 10];
}

const [width, height] = returnWidthAndHeight();
// width = 5, height = 10

Conclusion

Destructuring is a JavaScript expression that allows us to extract data from arrays and objects. In this article, we have explored the syntax and various ways we can use it in our code. Destructuring arrays and objects is something that will make your code a bit shorter and cleaner all over the place.

Discuss with community

Share

About the author

author_image

Angular by day. React by night. Full-stack when needed. I like blogging about web stuff. Co-organizer ngVikings.

author_image

About the author

Michael Karén

Angular by day. React by night. Full-stack when needed. I like blogging about web stuff. Co-organizer ngVikings.

About the author

author_image

Angular by day. React by night. Full-stack when needed. I like blogging about web stuff. Co-organizer ngVikings.

NxAngularCli
NxAngularCli
NxAngularCli

Featured articles

Angularpost
4 March 20218 min read
Angular Universal: real app problems

Angular Universal is an open-source project that extends the functionality of @angular/platform-server. The project makes server-side rendering possible in Angular. This article will discuss the issues and possible solutions we encountered while developing a real application with Angular Universal.

Angularpost
4 March 20218 min read
Angular Universal: real app problems

Angular Universal is an open-source project that extends the functionality of @angular/platform-server. The project makes server-side rendering possible in Angular. This article will discuss the issues and possible solutions we encountered while developing a real application with Angular Universal.

Read more
AngularpostAngular Universal: real app problems

4 March 2021

8 min read

Angular Universal is an open-source project that extends the functionality of @angular/platform-server. The project makes server-side rendering possible in Angular. This article will discuss the issues and possible solutions we encountered while developing a real application with Angular Universal.

Read more
Angularpost
3 March 20215 min read
View State Selector  - Angular design pattern

As a web developer you may have noticed a repetitive boiler plate code of displaying a loader while an asynchronous request is being processed, then switching to the main view or displaying an error. Personally, I noticed these repetitions both in my code and other developers I work with. And even worse than the repetitive code is the fact that there are no indications for missing state views (such as unhandled errors or a missing loader). <div *ngIf="data$ | async as data"> <ng-container *ng

Angularpost
3 March 20215 min read
View State Selector  - Angular design pattern

As a web developer you may have noticed a repetitive boiler plate code of displaying a loader while an asynchronous request is being processed, then switching to the main view or displaying an error. Personally, I noticed these repetitions both in my code and other developers I work with. And even worse than the repetitive code is the fact that there are no indications for missing state views (such as unhandled errors or a missing loader). <div *ngIf="data$ | async as data"> <ng-container *ng

Read more
AngularpostView State Selector  - Angular design pattern

3 March 2021

5 min read

As a web developer you may have noticed a repetitive boiler plate code of displaying a loader while an asynchronous request is being processed, then switching to the main view or displaying an error. Personally, I noticed these repetitions both in my code and other developers I work with. And even worse than the repetitive code is the fact that there are no indications for missing state views (such as unhandled errors or a missing loader). <div *ngIf="data$ | async as data"> <ng-container *ng

Read more
RxJSpost
26 February 20213 min read
RxJS: Why memory leaks occur when using a Subject

It's not uncommon to see the words 'unsubscribe', 'memory leaks', 'subject' in the same phrase when reading upon RxJS-related materials. In this article, we're going to tackle this fact and by the end of it you should gain a better insight as to why memory leaks occur.

RxJSpost
26 February 20213 min read
RxJS: Why memory leaks occur when using a Subject

It's not uncommon to see the words 'unsubscribe', 'memory leaks', 'subject' in the same phrase when reading upon RxJS-related materials. In this article, we're going to tackle this fact and by the end of it you should gain a better insight as to why memory leaks occur.

Read more
RxJSpostRxJS: Why memory leaks occur when using a Subject

26 February 2021

3 min read

It's not uncommon to see the words 'unsubscribe', 'memory leaks', 'subject' in the same phrase when reading upon RxJS-related materials. In this article, we're going to tackle this fact and by the end of it you should gain a better insight as to why memory leaks occur.

Read more