Sunday, August 14, 2016

Destructuring in ES2015

This is a first in a series of blog posts that will chronicle my exploration of the ECMA Script 2015 language update. The ES2015 is a specification which updates JavaScript with several additions to the language syntax. These improvements fall under the broad umbrella of ECMA Script 6 (ES6).

Why now?

I recently started working on a hobby project involving React and React Native which contain a lot of examples written in ES6.Hence, I thaught I would kill two birds with one stone and learn a bit about ES6 language features.

Important: I am in no ways a JS language expert and these blogs are a self learning tool (Caveat Emptor!)

What is Destructuring?

The process of extracting values from an object or an array [1]. It allows you to write concise code by:
  1. More cleanly handling functions which return multiple values
  2. More concisely access nested properties in objects

The syntax for destructuring in ES6 changes based on whether your working with an object or an array(Refer to Case#1 and Case#2 in the example below).

JS Sample on JSBIN 


When destructuring an Object JS will call toObject method on the left side of the expression.Hence, attempting to destructure undefined or null will cause an exception [1] [2].This means that primitives can be destructured too! (Refer to Case#5)

Loads of examples can be found here [4] and here [5].

I will be updating this post with more info once I get a bit of practice with this new syntax.

References


[1] http://exploringjs.com/es6/ch_destructuring.html
[2] http://www.ecma-international.org/ecma-262/6.0/#sec-toobject
[3] https://babeljs.io/docs/learn-es2015/
[4] https://ponyfoo.com/articles/es6-destructuring-in-depth
[5] https://gist.github.com/mikaelbr/9900818

No comments:

Post a Comment