Destructuring assignment makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
The object and array literal expressions provide an easy way to create ad-hoc packages of data. Once you’ve created these packages of data, you can use them any way you want to. You can even return them from functions.
One particularly useful thing you can do with destructuring assignment is to read an entire structure in a single statement, although there are a number of interesting things you can do with them, as shown in the section full of examples that follows.This capability is similar to features present in languages such as Perl and Python.
Trick 1: Swapping values between two variables without using the temporary variable.
I still remember when I was learning assembly language programming, one of my friend was so proud of showing off the XOR Swap Trick. It was indeed the coolest thing I saw then, since it saves 1 register. ;-)
var a = 1;
var b = 3;
[a, b] = [b, a];
Ha! One line does it all, and it is quite readable!
Trick 2: Parse a URL and get the parts from it using as few lines of code as possible.
var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
var [, protocol, fullhost, fullpath] = parsedURL;
Notices that we ignored the first value from the result, and we are able to extract and assign all of the parts of the URL in one line!