Last active
December 1, 2017 01:31
-
-
Save br3nt/3e25859021e57005add51bd1f50f7c2f to your computer and use it in GitHub Desktop.
JS destructuring assignment syntax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment | |
| // see: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/ | |
| var a, b, c, x, y, z, key, foo, bar, baz; | |
| // destructuring arrays (and default values) | |
| [a, b, c=5] = [10, 20]; | |
| a // 10 | |
| b // 20 | |
| c // 5 | |
| // swapping variable values | |
| [a, b] = [a, b] | |
| a // 20 | |
| b // 10 | |
| // ignoring vars | |
| var [a, , b] = [1, 2, 3]; | |
| a // 1 | |
| b // 3 | |
| // remainder of array | |
| var [a, ...b] = [1, 2, 3]; | |
| a // 1 | |
| b // [2, 3] | |
| // destructuring nested arrays | |
| [foo, [[bar], baz]] = [1, [[2], 3]] | |
| foo // 1 | |
| bar // 2 | |
| baz // 3 | |
| // destructuring arrays in method params | |
| atest = ([a, ...rest] = []) => rest | |
| atest([1, 2]) // [2] | |
| // destructuring objects (and default values) | |
| { x=5, y } = { y: 7 }; | |
| x // 5 | |
| y // 7 | |
| // remainder of object | |
| { a, ...b } = { b: 7 } // may need to be put in parenthases: ({ a, ...b } = { b: 7 }) | |
| a // undefined | |
| b // { b: 7} | |
| // assigning to new variable names | |
| {p: foo, q: bar = 2} = { p: 1 }; | |
| foo // 1 | |
| bar // 2 | |
| // destructuring objects in method params | |
| test = ({ a, ...rest } = {}) => rest | |
| test({a:1, b:2}) // {b:2} | |
| // computed property names | |
| key = 'z'; | |
| ({[key]: foo} = {z: 'bar'}); | |
| foo // bar | |
| // destructuring of invalid property names | |
| ({ 'fizz-buzz': fizzBuzz } = { 'fizz-buzz': true }); | |
| fizzBuzz // true | |
| // iteration | |
| var people = [ | |
| { | |
| name: 'Mike Smith', | |
| family: { | |
| mother: 'Jane Smith', | |
| father: 'Harry Smith', | |
| sister: 'Samantha Smith' | |
| }, | |
| age: 35 | |
| }, | |
| { | |
| name: 'Tom Jones', | |
| family: { | |
| mother: 'Norah Jones', | |
| father: 'Richard Jones', | |
| brother: 'Howard Jones' | |
| }, | |
| age: 25 | |
| } | |
| ]; | |
| for (var {name: n, family: {father: f}} of people) { | |
| console.log(`Name: ${n}, Father: ${f}`); | |
| } | |
| // "Name: Mike Smith, Father: Harry Smith" | |
| // "Name: Tom Jones, Father: Richard Jones" | |
| // destructuring with iterables/generators | |
| function* fibs() { | |
| var a = 0; | |
| var b = 1; | |
| while (true) { | |
| yield a; | |
| [a, b] = [b, a + b]; | |
| } | |
| } | |
| var [a, b, c, x, y, z] = fibs(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment