Created
October 14, 2019 17:17
-
-
Save johnborges/7c7389d61bd6408bebae6ca4da1c0f2e to your computer and use it in GitHub Desktop.
Cool ways of destructuring in JS
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
// skip items | |
let [a , , b] = [1, 2, 3]; | |
// quick swap variables | |
let a = 1; | |
let b = 3; | |
[a, b] = [b, a]; | |
// assignment without declaration | |
let y, x; | |
({y, z} = {y: 1, z: 2}); | |
// computed object property name and destructuring | |
let key = 'z'; | |
let {[key]: foo} = {z: 'bar'}; | |
console.log(foo); // "bar" | |
// combined array and object destructuring | |
const props = [ | |
{ id: 1, name: 'Fizz'}, | |
{ id: 2, name: 'Buzz'}, | |
{ id: 3, name: 'FizzBuzz'} | |
]; | |
const [,, { name }] = props; | |
console.log(name); // "FizzBuzz" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment