ES6 Everyday: Destructuring

We’ve got a really exciting one to close out our week!

Okay, so you know how to assign a variable:

var x = 30;

And then, of course, you know how to assign two variables:

var x = 30;
var y = 50;

With destructuring, we can do the following instead:

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

This is called the “array pattern” of destructuring. We can use it to return multiple values from a function like so:

function getCoords()
{
  return [30, 50];
}

var [x, y] = getCoords();
console.log(x); // 30
console.log(y); // 50

Alternatively, we can use the “object pattern”:

function getCoords()
{
  return { x: 30, y: 50 };
}

var {x, y} = getCoords();
console.log(x); // 30
console.log(y); // 50

Give it a spin in this ES6 fiddle.

Resources