Answer JS destructuring question (#14)

* Answer JS destructuring question

* Update README.md
This commit is contained in:
Filip Barakovski 2018-02-13 17:51:17 +01:00 committed by Yangshun Tay
parent 96d7a25629
commit d8da908263
1 changed files with 47 additions and 1 deletions

View File

@ -1567,7 +1567,53 @@ Use **higher-order function** to make your code easy to reason about and improve
### Can you give an example for destructuring an object or an array?
TODO
Destructuring is an expression available in ES6 which enables a succinct and convenient way to extract values of Objects or Arrays, and place them into distinct variables.
**Array destructuring**
```js
// Variable assignment
var foo = ['one', 'two', 'three'];
var [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"
```
```js
// Swapping variables
const a = 1;
const b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
```
**Object destructuring**
```js
// Variable assignment
const o = {p: 42, q: true};
const {p, q} = o;
console.log(p); // 42
console.log(q); // true
```
```js
// Assignment without declaration
let a, b;
({a, b} = {a: 1, b: 2});
```
###### References
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
* https://ponyfoo.com/articles/es6-destructuring-in-depth
### ES6 Template Literals offer a lot of flexibility in generating strings, can you give an example?