A real javascript ninja

Destructuring Assignments in JavaScript

How to swap two variables with 1 line of code

Nicholas Ortenzio
2 min readJul 27, 2013

--

Typically when you want to swap the contents of 2 variables, you need to create a 3rd variable to temporarily hold the value of the first variable to be re-assigned. I’m sure we've all done this before:

// the two values we want to swap
var a = 1, b = 2;
var c = a;
a = b;
b = c;

That’s mad basic, step off. I prefer to do things in as few lines of code as possible; even if it doesn’t work on 81% of all browsers. I present a 1-line swap:

// Two values that we want to swap
var a = 1, b = 2;
[a,b] = [b,a];

If you’ve leveled up your javascript stat to 99, after this line of code executes, a is equal to 2, and b is equal to 1. Otherwise,you’ve gotten an “Invalid left hand assignment error”. Keep trying (in firefox).

Break it down

JavaScript version 1.7 introduced a feature called “Destructuring Assignment”. Basically this allows you to assign values directly into variables contained in an anonymous array. The following code should make it easier to understand:

[a] = [1];
a.toString() // outputs “1"
[a, b] = [1, 2];
a.toString() // outputs “1"
b.toString() // outputs “2"

This can also come in handy when you want a function that returns multiple values. (Excuse the contrived example)

var getFirstAndLast = function(tag) {
var elms = document.getElementsByTagName(tag);
return (elms) ? [elms[0], elms[elms.length-1]] : [,]
}
// Without Destructuring Assignment
myArr = getFirstandLast(‘div’);
alert(myArr[0]); alert(myArr[1]);
// With Destructuring Assignment
[first, last] = getFirstAndLast(‘div’);
alert(first); alert(last);

Or if you’re working with Regular Expressions and capture groups, you’ve probably done something similar to this

// look for any string of digits following ‘def’
var results = /def(\d+)/gi.exec(‘abc123def456');
if (results) { alert(results[1]) }

Using Destructuring Assignments the code becomes cleaner (in my opinion)

// look for any string of digits following ‘def’
var [,result] = /def(\d+)/gi.exec(‘abc123def456');
if (result) { alert(result) }

So that’s Destructuring Assignments. AKA “next level shit”. If you’d like to read more, check out the Mozilla Developer page for JavaScript 1.7

Nicholas Ortenzio is a software developer and cup stacking champion.

--

--