Cool code tricks you can do with JavaScript Deconstruction

Swapping variable values in one statement, returning multiple values with the `return` statement.

John Paul Ada
2 min readOct 5, 2016

Deconstruction in JavaScript is a cool new feature introduced in ECMAScript 2015 a.k.a. ES6, which allows you to extract the contents of an array or an object to different variables, effectively deconstructing the array or object.

A simple example:

// Array Deconstruction
let [a, b] = [1, 2];
// Output: a = 1, b = 2
console.log(`a = ${a}, b = ${b}`);
// Object Deconstruction
let {x, y} = {x: 1, y: 2}
// Output: x = 1, y = 2
console.log(`x = ${x}, y = ${y}`);

Swapping variable values

To use deconstruction to swap you can do this:

let a = 1, b = 2; // a = 1, b = 2// Swapping
[a, b] = [b, a];
// Output: a = 2, b = 1
console.log('a = ' + a + ', b = ' + b);

This code transfers the first value of the array on the right (which is b) to the first value of the array on the left (which is a) and so on. In effect, the variables are swapped, without the usual `temp` variable! Awesome, right?

Returning multiple values

You can return multiple multiple values in JavaScript by deconstructing the array or object returned by a function.

function vectorDotScalar(vector, scalar) {
return {x: vector.x * scalar, y: vector.y * scalar, z: vector.z * scalar};
}
const v1 = {x: 1, y: 2, z: 3};
const s1 = 2;
const {x, y, z} = vectorDotScalar(v1, s1);// Output: x = 2, y = 4, z = 6
console.log('x = ' + x + ', y = ' + y + ', z = ' + z);

The vectorDotScalar function returns an object which is then deconstructed into the x, y, and z variables. You can use this pattern with arrays too!

Also, if you liked this post, click the little green heart down below! Many thanks! :D

Personal Pages: http://johnpaulada.github.io

--

--