From d8da9082634e8db5fb23f64d625a9f4e479b55d0 Mon Sep 17 00:00:00 2001 From: Filip Barakovski Date: Tue, 13 Feb 2018 17:51:17 +0100 Subject: [PATCH] Answer JS destructuring question (#14) * Answer JS destructuring question * Update README.md --- README.md | 48 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 85cce4871..03f194013 100644 --- a/README.md +++ b/README.md @@ -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?