„The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.“
So why and how to use it:
In the current version of JavaScript, ES5, you would do something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Objects with animals anyObject = { weight: 23, sound: 'woof', name: 'Alex' } makeSound(anyObject) function makeSound(options) { var species = options.species || 'animal'; // In the case options.species is undefined, assign a generic 'animal' to it. var sound = options.sound; console.log('The ' + species + ' says ' + sound + '!'); // returns "The animal says woof!" } |
Of course we could go without declaring the local variables species and sound inside the makeSound() function, but for the purpose of readability I’d prefer this way.
Now let’s take a look how to improve the makeSound() function in ES6:
1 2 3 4 5 6 7 8 9 10 11 |
// Objects with animals anyObject = { weight: 23, sound: 'woof', name: 'Alex' } makeSound(anyObject) function makeSound({ species: 'animal', sound}) { console.log('The ' + species + ' says ' + sound + '!'); // returns "The animal says woof!" } |
And this is just amazing! We can assign the attributes of an object to local variables direct in the functions signature. Furthermore we can give default values for the case a attribute is undefined.
This is much better to read and understand than the above approach in ES5.
Btw, when you want to test ES6 features, I suggest using Babel. Use it just like this:
1 |
$ babel example.js | node |
More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment