Working with the destructuring assignment in JavaScript

Written by
Published on
Category

The destructuring assignment in JavaScript is one of those things that you might never see yourself using, but that might be just the thing you need on that rare blue moon.

It's designed to have you write less code when performing common everyday tasks, such as extracting object properties, cloning arrays or even swapping values.

So it's good to have it added to your toolkit.

Destructuring arrays

Destructuring does just what it's namesake entails. The syntax takes apart a collection of items, such as in arrays, into individual elements and puts them into their own variables.

let [a,b] = [1, 2, 3, 4];

console.log(a); // 1

console.log(b); // 2

You can also use the . . . notation in order to extract multiple values out from a given array.

let [...c] = [1, 2, 3, 4];

console.log(c); // [1, 2, 3, 4]

This might seem like a trivial assignment, but it's actually a very useful one. Using the . . . notation to destructure an array will not only copy the values of the right side to the left side variable, but it will also create a deep-copy of the right side array.

let arr = [1, 2, 3];

let [...c] = arr;

console.log(arr); // 1, 2, 3

console.log(c);   // 1, 2, 3

Which means you now have 2 separate arrays with the same data in each. Just that alone, makes destructuring an invaluable feature in JavaScript.

Destructuring objects

You can also destructure object variables as well similar to how you would with arrays above, with a slight change in the syntax.

let car = { make: 'Honda', model: 'Civic'};

let {make, model} = car;

console.log(make);   // 'Honda';

console.log(model);  // 'Civic'

Note that the variable names given in the left side declaration must match the property names in the given object, otherwise it will be initialized as undefined.

Just as with arrays, you can also make use of the ... notation in order to copy the remaining properties in a given object.

let car = { make: 'Honda', model: 'Civic', year: 1999, color: 'Black'};

let {make, model, ...props} = car;

console.log(make);   // 'Honda';

console.log(model);  // 'Civic'

console.log(props);  // {year: 1999, color: 'Black'}

In this case, the ...props variable will be initialized to a new object containing any remaining destructured properties.

Assign new variable names

It is possible to assign destructured object properties to brand new variable names. The syntax is a bit convoluted and overall it might make your code harder to read, but it is possible.

let obj = {a: 10, b: 20};

let {a: new_a, b: new_b} = obj;

console.log(new_a);  // 10

console.log(new_b);  // 20

Default parameters

Declared variables can also include defaults, in case the destructured object at any point in time returns an undefined value.

let numbers = [1, 2];


let [a, b, c=3] = numbers;

console.log(a);  // 1

console.log(b);  // 2

console.log(c);  // 3

In this example, variable c will be initialized to the value of 3 if no destructured item is found.

Swapping variables

A very useful trick that you can perform using the destructured assignment syntax, is the ability to swap the values of 2 different variables in a single statement.

As any programmer knows, swapping values for the most part involves creating a third temporary variable to house the value of one of the variables in order to preserve the value during the first swap.

let num1 = 1;
let num2 = 2;

[num1, num2[ = [num2, num1];

console.log(num1);  // 2

console.log(num2);  // 1

When to use it

More than anything, the destructuring syntax helps developers use less code overall when performing relatively simple tasks, such as working with object properties, swapping items in place and deep-cloning arrays and objects.

A common scenario for example is passing objects as arguments to functions. Often times, it might be simpler to include the entire object as an argument, and to then let the function decide just which properties it will use.

let car = {make: 'Honda', model: 'Accord'};

function f({make}){
  console.log(make); // 'Honda'
}

The syntax takes some getting used to, particularly if you begin to work with nested arrays and objects. But once you do, you will begin to notice just how much less code you have to type in order to accomplish some relatively simple tasks.

Comments

No messages posted yet

Developer Poll

Q:

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post