Before you go, check out these stories!

Hackernoon logoWhat You Should Know About Assignment Destructuring in ES6 by@jsborked

What You Should Know About Assignment Destructuring in ES6

Author profile picture

@jsborkedJust Chris

JavaScript ES6 has a variety of new features when compared to its predecessor JavaScript ES5. Let’s take a look at Assignment Destructuring and how it helps programmers simplify their code.

[a,b] = [1, 2]
// a == 1
// b == 2
{a,b} = {a:3, b:4}
// a == 3
// b == 4

Assignment Destructuring allows for easy binding of the same properties to as many variables as desired. It also works in both arrays and objects, further expanding its scope. It makes pulling out specific properties from different objects an easy task and also allows for aliasing of properties too.

Objects default to undefined if no data is provided for that object.

[a, b, c] = [5, 6];
// c === undefined

We can ignore certain values if necessary.

var [a, , b] = [1, 2, 3];
console.log(a, b); // 1 3

We can combine values.

[a, ...b] = [1, 2, 3];
// b == [2, 3]

Assignment destructuring enables operations on objects, such as pulling values out of an object, using this short-hand syntax.

o = {p1: 'foo', p2: 'bar'};
var {p1, p2} = o;
// p1 == 'foo'
// p2 == 'bar'

Assignment Destructuring also allows for swapping of variables in a single function, but unlike others, it allows the same without the use of a temp variable.

var a = 1, b = 2;
[b, a] = [a, b];
// a == 2
// b == 1

Clear and smaller code is its own reward. Assignment Destructuring is a boon for programmers as it helps them to prevent writing extra code, thereby saving time and effort.


The Noonification banner

Subscribe to get your daily round-up of top tech stories!