protips

Logo

This site lists the protips that we shared with students during our courses

View the Project on GitHub appliedtechnology/protips

Fun with destructuring in JavaScript

One of the really powerful new tools that we get in EcmaScript 6 is destructing. This is super powerful since we can write tighter code that allows us to pick out values from object (or arrays) in a much easier way.

For example, consider an object like this:

const options = {
  pageType: 'A4',
  printerName: 'Marcus Laser desk 4',
  orientation: 'landscape',
  type: 'Laser',
  properties: [
    {prop1: "a prop"},
    {prop2: "a prop"},
    {prop3: "a prop"},
    {prop3: "a prop"},
  ]
};

But you are only interested in the printerName and the type, then in old JavaScript our grandparents would have to write this:

var printerName = options.printerName;
var type = options.type;

But with the advent of ES6 destructuring we can write this:

const {printerName, type} = options;

and be done with it.

Destructuring objects in parameters

It gets even cooler when we use destructuring for things that we take as parameter. Consider this function that your grandpa wrote, using EcmaScript 5:

function printPrinterNameAndType(options) {
  var printerName = options.printerName;
  var type = options.type;

  console.log('The printer ' + printerName + ' is of type: ' + type);
}

You can now destructure the parameters that you are interested in from the options object right in the function declaration, making your code into a one-liner. You also threw in some arrow functions and template string just for the heck of it.

const printPrinterNameAndType = ({printerName, type}) {
  console.log(`The printer '${printerName}' is of type: '${type}'`);
}

Array destructuring

That was destructuring objects, but we can also destructuring arrays. That gives us the same power as we get from destructuring but another benefit, with arrays specifically, of this is to be able to give positions, in the array, names.

Consider this array, containing some properties for a person.

const personData = ['7210009XXXX', 'Marcus', '47', 'Strålgatan 23', '5224 2234 2234 2511'];

You can probably make out what those positions contains, but a good practice is to pick this out into variables, when we want to use it. Like this, as grandpa would have written it:

var personalNumber = personData[0];
var name = personData[1];
var age = personData[2];
var address = personData[3];
var creditCardNumber = personData[4]; // WHA?! Who put that in there?

But you can, using destructuring, write this much tighter, and also skip the values that ARE NONE OF YOUR BUSINESS…

const [, name, , address] = personData;

And again, the real power, comes from when we pass this to a function:

const printRelevantPersonData = ([, name, , address]) => console.log(`${name} lives at ${address}`);

// call it with the data array
printRelevantPersonData(personData);

Going insane with arrays of arrays

But where this really shines is when you have arrays of arrays. For example, let’s say that we instead read a list of people, but only are interested of the first one, since that person is the most important in the universe:

const people = [
  ['7210009XXXX', 'Marcus', '47', 'Strålgatan 23', '5224 2234 2234 2511'],
  ['7710009XXXX', 'Elin', '{Question rejected}', 'Strålgatan 23', '5224 2234 2234 2511'],
  ['0810009XXXX', 'Abbe', '14', 'Strålgatan 23', '5224 2234 2234 2511'],
  // etc.
]

Grandpa would have needed to write:

var mostImportantPersonName = people[0][1];
var mostImportantPersonAddress= people[0][3];

But you do all of that in one sweep, using array destructuring:

const [[, mostImportantPersonName, , mostImportantPersonAddress]] = people
console.log(mostImportantPersonName);

Of course, if pushed you can also pick out other people of that array…

const [, [, secondMostImportantPersonName, , secondMostImportantPersonAddress]] = people
console.log(secondMostImportantPersonName);

Summary

Destructuring is a very powerful way to write not only shorter but also more readable code.