Skip to content

Instantly share code, notes, and snippets.

@johnborges
Created October 14, 2019 17:17
Show Gist options
  • Save johnborges/7c7389d61bd6408bebae6ca4da1c0f2e to your computer and use it in GitHub Desktop.
Save johnborges/7c7389d61bd6408bebae6ca4da1c0f2e to your computer and use it in GitHub Desktop.
Cool ways of destructuring in JS
// 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