Quantcast
Viewing all articles
Browse latest Browse all 10

Destructuring assignments in JavaScript 1.7

Destructuring assignments are great for time saving methods of assigning values to variables. They make for shorter code, and shorter code is less error prone.

A destructuring assignment essentially allows you to arrange variables in an arrayesque manner, and assign them an array. What this does is actually assign the items in the array to each variable in one go. This is much easier to explain with an example.

Say we have two variables:

var variable1 = 10, variable2 = 20;

Now, we want to assign them two new values. By putting those variables inside an array-like structure before the assignment operator, we can do this in one statement instead of two:

[variable1, variable2] = [30, 40];

Now, variable1 is 30, and variable2 is 40. We can use this to take all of the items of an array returned from a function and put them in individual variables:

var color1, color2, color3;
var fnGetColors = function() {
	var arrColors = ['red', 'green', 'blue'];
	return arrColours;
};
[color1, color2, color3] = fnGetColors();

Or to swap the values of two variables, which previously would have required a temporary variable to use for storage:

var strBlack = '#FFFFFF';
var strWhite = '#000000';
//Oops, wait - that's not right
[strBlack, strWhite] = [strWhite, strBlack];

Sadly, support for JavaScript 1.7 is patchy. Internet Explorer, even in version 8, still only supports JavaScript 1.5. This kind of code could be useful if you were writing extensions for Firefox though, or had control over your user base (perhaps in an Intranet). I include it here just for interest – one day we’ll be able to use it!

Further reading:
New in JavaScript 1.7 – MDC
JavaScript Versions on Wikipedia


Viewing all articles
Browse latest Browse all 10

Trending Articles