DEV Community

Mohana Naga Venkat Sayempu
Mohana Naga Venkat Sayempu

Posted on

Destructuring

Destructuring, or "destructuring assignment syntax" describes the syntactically efficient extraction and declaration of new variables in the local scope from arbitrarily complex data structures.

Object Destructuring

When destructuring, object literal notation syntax is used on the left side of the assignment operation to both describe the target data structure and name the new local variables to be declared.

var data = {
  foo: 'foo',
  bar: 'bar',
  baz: {
    qux: 'qux'
  }
};

var {foo:newFoo,bar:newBar,baz:{qux:newQux}} = data;

newFoo; // 'foo'
newBar; // 'bar'
newQux; // 'qux'

A shorthand syntax can be used when the desired local variable names are the same as the object keys in the data. This has the benefit of not having to name target keys twice as in var foo = bar.foo and so minimises typing and errors.

var data = {
  foo: 'foo',
  bar: 'bar'
};

var {foo,bar} = data;

foo; // 'foo'
bar; // 'bar'

Array Destructuring

Array literal notation syntax can be freely mixed with object literal notation syntax while destructuring.

var data = ['foo','bar',['baz']];

var [foo,bar,[baz]] = data;

foo; // 'foo'
bar; // 'bar'
baz; // 'baz'

Iterator Destructuring

Array literals can be used to destructure any iterable object.

var set = new Set().add('a').add('b').add('c');

var [x,y,z] = set;
console.log(x,y,z); // a b c

Loop Destructuring

We can destructure in a loop header to efficiently declare loop variables.

let map = new Map();
map.set('a',1);
map.set('b',2);

for (let [k,v] of map) {
  console.log(`key = ${k}, value = ${v}`);
}

Parameter Destructuring

Destructuring can also be used inline in function parameters.

function f ({foo,bar}) {
  console.log(foo);
  console.log(bar);
}

f({foo:'foo',bar:'bar'}); // 'foo' 'bar'

Happy Coding ๐Ÿ˜€

Top comments (0)