This page looks best with JavaScript enabled

Destructuring In JavaScript Can Make Your Code Short And Cleaner

 ·  ☕ 6 min read  ·  ✍️ Adesh

What Problem Destructuring Really Solve?

Okay, we are now fine with the definition of destructing - extracting values from an array or object. But, what problem it can solve? Where is this beneficial? What is the use-case of this? These doubts must be coming in your mind. Let me clear your doubts by taking an example.

Object Destructuring

Let’s suppose you have a below JavaScript object.

1
2
3
4
5
6
7
8
9
const employee = {
  first: "James",
  last: "Boss",
  country: "USA",
  city: "New York",
  twitter: "@james",
};
const first = employee.first;
const last = employee.last;

Now, look at last two lines - line 8 and 9. If you notice, we are repeating the same code to get the employee first and last name. So, we are repeating this code over and over again, to get the properties of an object to declare variables.

Okay, we got the problem now. So, how isdestructuring going to sort out this? Destructuring allows us to destructure the object into a single line, to make different variables, without repeating the same code over and over again.

1
const { first, last } = employee;

This new syntax is called Destructuring, getting new variables in a single line.

Let me explain, what is going on above line of code. This says, create two variables firstand last, and take it from the objectemployee. We’re taking the first property and the lastproperty and putting them into two new variables that will be scoped to the parent block (or window!).

So, the output of below line of code will be like this:

1
2
console.log(first); //James
console.log(last); // Boss

This is really useful in many cases, where we have simple object. What about the complex object?

Nested Object Destructuring

Let’s try this with a same complex object, where we want to access nested properties.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const employee = {
  first: "James",
  last: "Boss",
  country: "USA",
  city: "New York",
  twitter: "@james",
  links: {
    social: {
      facebook: "https://facebook.com/jamesboss",
      instagram: "https://instagram.com/ijamesboss",
    },
    web: {
      blog: "www.zeptobook.com",
    },
  },
};

Now, we want to get employee’s facebook and instagram account details. We will normally write code like this:

1
2
const instagram = employee.links.social.instagram;
const facebook = employee.links.social.facebook;

Again, this is really very weird. We have to dive into nested object nodes to get the properties.

Let’s resolve this by using destructuring feature.

1
2
const { instagram, facebook } = employee.links.social;
console.log(instagram, facebook);

In the above code, we have seen how object destructuring works. Let’s explore this in the case of an array as well.


Array Destructuring

Let’s take a very simple example of array destructuring, and how we destructure them into variables.

Basic variable assignment

1
2
3
4
5
6
7
8
let names = ["Robert", "James"];

//In a normal way to declaring variables
let name1 = names[0];
let name2 = names[1];

console.log(name1);
console.log(name2);

In the above code in line 4 and 5, we repeat the same mistake. Let’s do it in a destructure way.

1
2
//In a destructure way to declaring variables
let [name1, name2] = names;

With default value

1
2
3
4
5
var x, y;

[x = 50, y = 70] = [10];
console.log(a); // 10
console.log(b); // 70

Swapping variables without any temporary variable

In normal swapping, we need a temporary variable to swap two variable. Let’s see how we swap them using destructuring.

1
2
3
4
5
6
var x = 10;
var y = 30;

[x, y] = [y, x];
console.log(x); // 30
console.log(y); // 10

This is how destructuring helps in an array as well.


Smart way of passing function parameters

Sometimes, we have functions with a lot of parameters. Let’s take such a function in our example. Suppose, we have a function with a lot of parameters.

This is very traditional, or you can say bad way of writing function parameters.

1
2
3
function smartFunc(name = "Untitled", width = 50, height = 60, items = []) {
  // ...
}

One of the problems with this function is order of the parameters. In modern editors, we have smart IntelliSense feature, which can help us to remember the order of each parameter in a function. But, in case, where we don’t have IntelliSense feature, it is very hard to remember the order of the parameters with their default values.

Let’s say, we want to pass few parameters with keeping default values, so you would call the function like below, which looks ugly and not readable.

1
smartFunc("test", undefined, undefined, ["item1", "item2"]);

Now, let’s see how destructuring can help us the this problem. There is a very smart way of passing parameters without such hurdles. Take a look at the below code.

Pass parameters as an object

Let’s first create an object with all parameters as properties of this object, and pass this object in the function call.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// Create an object
let funcParams = {
  title: "Smart Func",
  items: ["Item1", "Item2"],
};

// function will automatically destructure them into parameters
function smartFunc({
  title = "Untitled",
  width = 50,
  height = 60,
  items = [],
}) {
  //...
}

// pass object into function
smartFunc(options);

Now, our smartFunc will automatically destructure the object properties in the function parameters. Cool!

Pass no parameters at all, use default parameters

In case, if you don’t want to pass any parameter, and use default values of the existing function, so call the function like below:

1
2
3
4
// pass  an empty object into function
smartFunc({});

smartFunc(); // will get an error here

There is another way to get rid of {} in function callsmartFunc({}) Let’s do a small change in our function declaration.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// function will automatically destructure them into parameters
function smartFunc({
  title = "Untitled",
  width = 50,
  height = 60,
  items = [],
} = {}) {
  //...
}

// call function without empty object
smartFunc();

Summary

So, we see, how destructuring is very helpful in small cases. How smartly you can work with arrays, objects, and functions. Destructuring sneaks into your everyday use of the language, quietly making your code a bit shorter and cleaner all over the place.

Further Reading

This Is Why Learning New JavaScript ES6 Syntax Is So Famous!

Eleven Ways To Learn Javascript Array Iteration Effectively

JavaScript Fundamentals Every Beginner Should Know

Share on

Adesh
WRITTEN BY
Adesh
Technical Architect