ES6: Destructuring

With the start of 2016, it seems that tutorials, blog posts, and documentation are using ES6 aka ES2015 more and more. If you haven’t made the transition yet, now is the time to start. I’ve been writing a series of blog posts on ES6 to help you make that transition. Today, I’ll be discussing a feature called destructuring.

Overview

Destructuring allows us to extract and assign data from objects and arrays using a syntax that mirrors the construction of of array and object literals.

Destructuring Arrays

Using the destructuring pattern with arrays, you can assign multiple independent variables in a single declaration, without targeting specific elements of the array

var foo = [1,2,3];
//without destructuring
var a = foo[0];
var b = foo[1];
var c = foo[2];
//same with destructuring
var [a,b,c] = foo;

One extra helpful user for destructuring is the ability to quickly swap variables. This eliminates the need to create a temporary holder for an element when swapping values in an array of object.

var unsortedArray = [2,1,3]
//sorting without destructuring 
for (var i=0; i<unsortedArray.length; i++){
var temp = unsortedArray[i];
unsortedArray[i]=unsortedArray[i+1];
unsortedArray[i+1]=temp;
}
//sorting with destructuring 
for (var i=0; i<unsortedArray.length; i++){
[arr[i], arr[i+1]] = [arr[i+1], [arr[i]];
}

Destructuring Objects

Of course, you can also use objects for destructed assignment. Instead of matching array indices, this pattern matches object properties

var obj = {a:1, b:2}
var {b:bar, a:foo} = obj;
console.log(foo);
//1
console.log(bar);
//2

Only Extracting Part

With arrays, you can select only just a portion:

var array = [a:1, b:2, c:3]
var [a,b] = array;
console.log(foo, bar);
//1
//2

With objects, you can select only those properties you are interested in:

var obj = {a:1, b:2, c:3}
var {a:foo, c:bat} = obj;
console.log(foo, bat);
//1
//3

Nesting

You can also make use of nested structures:

var obj = {a:{c:1}, b:[2,3]};
var {a:{c:foo}, b:[bar, bat]};
console.log(foo, bar, bat);
//1,2,3

Functions

Lastly, you can assign variables using return values from functions, as you usually would.

var f = funciton(){
return [1,2,3]
}
var [a,b,c] = f();
console.log(a,b,c);
//1,2,3
Show your support

Clapping shows how much you appreciated Zan Rosenthal’s story.