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:
- More cleanly handling functions which return multiple values
- 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).
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