programming JavaScript Oct 28, 2015

ES6 Destructuring

  • Destructuring works exactly as its syntax suggests
  • The only tricky point is object destructuring without variable declaration
    • with declaration: let {x: a} = {x: 'a'};
    • without declaration: ({x: a} = {x: 'a'}); (assuming that a has already been declared)
    • It's simply because a bare object is not valid syntax
  • Default arguments and destructuring:
/* prop === 'default' */ let { prop = 'default' } = {};
/* prop === 'value' */   let { prop = 'default' } = { prop: 'value' };
/* name === 'value' */   let { prop: name = 'default' } = { prop: 'value' };
1
2
3
  • Default arguments also work for arrays:
    • let [head = "default"] = [];
  • Default values for destructuring assignment is especially useful as function arguments defaults:
let destructObject = ({ a = 'a', b = 'b' } = {}) => [a, b];
let destructObject = ({ a: arg1 = 'a', b: arg2 = 'b' } = {}) => [arg1, arg2];
destructObject({});       // ['a', 'b]
destructObject({ b: 'c' }); // ['a', 'c']
1
2
3
4

#javascript #es2015

Follow me on Twitter, GitHub.

unless otherwise stated, all content & design © copyright 2019 victor felder