Friday, April 27, 2007

New things in Javascript 1.7

As the Javascript is becoming more than more mature, it is starting to show some really neat features that you can find in programming other scripting language, such as Ruby and Python. Here, I will just pick a couple of them to do some neat tricks that we would probably find useful.

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. ;-)

Now, how can you do it in Javascript? Use Destructing Assignment.


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 url = 'http://hungryfools.com/2007/4/27/new-things-in-javascript-1-7';
var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
var [, protocol, fullhost, fullpath] = parsedURL;
alert(protocol);
alert(fullhost);
alert(fullpath);

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!

For detailed explanation of what’s new in Javascript 1.7, please visit http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7.

No comments: