Getting Started with JavaScript ES6 Destructuring

Lets take a closer look at the new syntax that ES6 brings to help with more explicit variable and argument declaration and assignment. The current state of affairs is pretty straight forward: on the left hand side you have a variable name, on the right you have an expression which, among other things, can be an array: [ ] or an object literal: { }. Destructuring assignment allows us to have an expression like variable declaration on the left hand side describing which values to extract from the right hand side. Sounds a bit confusing? Lets look at the specific examples.

Array Destructuring

Lets say we have a value variable which is [1, 2, 3, 4, 5] and we want to declare variables that contain first three elements. Traditionally each variable would be declared and assigned separately like so:

Having these variables, our original value might now be represented as [el1, el2, el3, 4, 5] and, since we don’t care at the moment about last two values, as something like [el1, el2, el3]. ES6 allows us to use this expression now on the left hand side to achieve the same declaration as above:

Spread operator is where things get really interesting. Spreads, otherwise knows as the “rest” pattern allow you to grab “remaining values” from the array. In the example below tail receives all remaining array elements which is [4, 5].

Bottom Line

ES6 destructuring brings in much needed syntax modernizations to JavaScript. It improves readability and reduces amount of code necessary to for expressive declarations.

ES6 Today

How can you take advantage of ES6 features today? Using transpilers in the last couple of years has become the norm. People and large companies no longer shy away. Babel is an ES6 to ES5 transpiler that supports all of the ES6 features.

If you are using something like Browserify in your JavaScript build pipeline, adding Babel transpilation [takes only a couple of minutes](https://babeljs.io/docs/using-babel/#browserify). There is, of course, support for pretty much every common Node.js build system like Gulp, Grunt and many others.

What About The Browsers?

The majority of browsers are catching up on implementing new features but not one has full support. Does that mean you have to wait? It depends. It’s a good idea to begin using the language features that will be universally available in 1-2 years so that you are comfortable with them when the time comes. On the other hand, if you feel the need for 100% control over the source code, you should stick with ES5 for now.