Destructuring Assignment

Object and Array are the two frequently used data structures of JavaScript.

With the help of the objects, you can create an entity storing data items by key. With the help of the arrays, you can assemble data items into an ordered collection.

In case of passing those to a function, it might need an object and array not as a whole but some individual pieces.

The literal expressions of the object and the array allow creating ad hoc packages. Here is the syntax:

const x = [1, 2, 3, 4, 5];

The destructuring assignment is a unique syntax that helps “to unpack” objects or arrays into a group of variables. Destructuring can also operate efficiently with complex functions, default values, and more.

The destructuring assignment uses the following syntax:

const x = [1, 2, 3, 4, 5];
const [y, z] = x;
console.log(y); // 1 
console.log(z); // 2

You can find similar features in other languages too. For example, in Python or Perl.

Now, let’s have a look at the example of the array destructure into variables:

// we have an array with the name and surname
let arr = ["John", "Doe"];
// destructuring assignment
// sets firstname = arr[0]
// and surname = arr[1]
let [firstname, surname] = arr;
console.log(firstname); // John
console.log(surname); // Doe

As a result, it is possible to work with variables instead of array members.

will work even greater if you combine it with split or other methods for array-returning:

let [firstName, surname] = "John Doe".split(' ');

Note that destructuring is not the same as “destructive”.

We call it destructuring as it “destructurizes” through the method of copying items into variables.

Here is a shorter way to write:

// let [firstName, surname] = arr;
let firstName = arr[0];
let surname = arr[1];

Take into consideration that you can throw away unwanted elements by using an extra comma, like this:

// second element is not needed
let [name, age , profession] = ["David", "23", "programmer"];
console.log(profession); // programmer

It can work with any iterable on the right-side:

let [a, b, c] = "abc"; // ["a", "b", "c"]
let [one, two, three] = new Set([1, 2, 3]);

Moreover, you can use any assignables at the left side.

For example, the property of an object:

let user = {};
[user.name, user.surname] = "John Doe".split(' ');
console.log(user.name); // John

Another useful thing is that it is possible to use the Object.entries(obj) method with destructuring for looping over keys-and-values of an object.

Here is an example:

let user = {
  name: "Maria",
  age: 25
};
// loop over keys-and-values
for (let [key, value] of Object.entries(user)) {
  console.log(`${key}:${value}`); // name:Maria, then age:25
}

The rest ‘…’

In case it is necessary to get not only the first values but also to assemble all the followings, you have the option of adding another parameter for getting “the rest” by just using three dots “…”, like this:

let [name1, name2, ...rest] = ["John", "Doe", "doctor", "surgeon"]; 
console.log(name1); // John
console.log(name2); // Doe
// Note that type of `rest` is Array.
console.log(rest[0]); // doctor
console.log(rest[1]); // surgeon
console.log(rest.length); // 2

Default Values

In case there are fewer values in the array than variables in the assignment, no error will occur. The values that are absent will be considered undefined:

let [firstName, surname] = [];
console.log(firstName); // undefined
console.log(surname); // undefined

If you want a default value for replacing the one that is missing, use the = sign, as follows:

// default values
let [name = "David", surname = "Smith"] = ["Peter"];
console.log(name); // Peter (from array)
console.log(surname); // Smith (default used)

Destructuring an Object

You can use the destructuring assignment with objects, as well, by using the following basic syntax:

let {  var1,  var2} = {  var1: …,  var2: …}

On the right side, there is an existing object that is necessary to split into variables. On the left side, there is a pattern for matching properties. The three dots sign {...} includes a group of variable names.

Here is an example:

let options = {
  title: "Car",
  model: "BMW M5",
  year: 2020
};
let {
  title,
  model,
  year
} = options;
console.log(title); // Car
console.log(model); // BMW M5
console.log(year); // 2020

The properties options.title, options.width and options.height are assigned to matching variables. The arrangement doesn’t matter. This option will also work:

// changed the order in let {...}
let {
  year,
  model,
  title
} = {
  title: "Car",
  model: "BMW M5",
  year: 2020
}

For assigning a property to a variable with different name, then you can act like this:

let options = {
  title: "Car",
  model: "BMW M5",
  year: 2020
}; 
// { sourceProperty: targetVariable }
let {
  model: m,
  year: y,
  title
} = options; 
// width -> m
// height -> y
// title -> title 
console.log(title); // Car
console.log(m); // BMW M5
console.log(y); // 2020

For possible missing properties, you have the option of setting default values using the sign of “=”, as follows:

let options = {
  title: "Car"
}; 
let {
  model = "BMW M5",
  year = 2020, 
  title
} = options; 
console.log(title); // Car
console.log(model); // BMW M5
console.log(year); // 2020

The default values might be any expressions or function calls.

In case there is a complex object with a range of properties, you may choose to extract what you need, as follows:

let options = {
  title: "Car",
  model: "BMW M5",
  year: 2020
};
// only extract title as a variable
let {
  title
} = options; 
console.log(title); // Car

The Rest Pattern “…”

Another scenario can also happen: the quantity of the object properties is more than the variables you have. In such cases, you can use the rest pattern. But, note that it works only on modern browsers.

Here is the example:

let options = {
  title: "Book",
  page: 200,
  species : "scientific"
}; 
// title = property named title
// rest = object with the rest of properties
let {
  title,
  ...rest
} = options; 
// now title="Book", rest={page: 200, species: scientific}
console.log(rest.page); // 200
console.log(rest.species); // scientific

Nested Destructuring

Imagine that an array or an object includes other nested arrays or objects. More complex, left-side patterns might be used for extracting deeper portions.

In the example below, options contain another object in the property views and array in the property items:

let options = {
  views: {
    model: "sport",
    year: 2020
  },
  items: ["Car", "Bike"],
  extra: true
}; 
// destructuring assignment split in multiple lines for clarity
let {
  views: { // put size here
    model,
    year
  },
  items: [item1, item2], // assign items here
  title = "Car&Bike" // not present in the object (default value is used)
} = options; 
console.log(title); // Car&Bike
console.log(model); // sport
console.log(year); // 2020
console.log(item1); // Car
console.log(item2); // Bike

It’s important to know that all the properties of options object except extra (it’s absent at the left side), are assigned to matching variables.

So, the model, year, item1, item2, and title are of the same value. But, no variables exist for views and items.

The Parameters of Smart Function

Sometimes a function has many parameters, and most of them are optional. But, let’s see that a function creates a menu. It will have a height, width, items list, a title, and more.

We don’t recommend you to write the function, like this:

function showBook(title = "Javascript", page = 200,  species : "programming"
, items = []) {
  // ...
}

The main problem is remembering the order of the arguments. Another problem is to find a way of calling a function when the majority of the parameters are good by default.

The most optional action is passing parameters as an object. The function will destructurize them into a variable at once, like this:

// we pass object to function
let options = {
  title: "Js book",
  items: ["Item1", "Item2"]
};
function showBook({
  title = "Javascript",
  pages = 200,
  species  = "programming",
  items = []
}) {
  // title, items – taken from options,
  // pages, species – defaults used
  console.log(`${title} ${species} ${pages}`); // Javascript programming 200
 console.log(items); // Item1, Item2
}
showBook(options);

There is another, more complex way of destructuring, including nested objects and colon mappings.

For instance:

let options = {
  title: "Js  book"
}; 
function showBook({
  title = "Javascript",
  p = 200, //pages goes to p
  s = "programming", // species goes to s
}) {
  console.log(`${title} ${s} ${p}`); // Javascript programming 200
} 
showBook(options);

The full syntax will look like this:

function ({
  incomingProperty: varName = defaultValue
    ...
})

As you can see, it’s the same as for a destructuring assignment.

Then, for the parameters’ object, there will be a variable varName for incomingProperty.

Destructuring like this considers that showBook() has no argument. In case you want all the values by default, then specify an empty object, like this:

showBook({}); // ok, all values are default
showBook(); // this would give an error

It is possible to fix it by setting {} the default value the object of parameters.

For instance:

function showBook({
  title = "Book",
  species = "programming",
  pages = 200
} = {}) {
  console.log(`${title} ${species} ${pages}`);
}
showBook(); // Book programming 200



Do you find this helpful?

Related articles