Saturday 24 September 2011

Destructuring Assignment

I've been keen of Rhino since the first time I knew about it, many years ago. At that time JavaScript was not by far the popular language that it's now, and being able to run a JavaScript shell and do some of your normal coding tasks with it was not in most people's agenda (for example just think that 95% of the WSH samples that you find on the net are VB instead of JavaScript).

Today I paid a visit to their site to see if there was something new, and to my delight I found version 1.7R3 there. I immediately jumped to the "What's new" section, and from there to the JavaScript 1.8 section. And there I found one of those brilliant ideas that once you come across them think how it is that humanity has lived for so long without them :-)
Changes in destructuring for..in

I've known the concept of destructuring assignment since the times I used to do some Python coding, it's a simple and powerful idea that I though only applied to function returns and swapping values

var [a, b] = function(){
return ["val1", "val2"];
};


so when I found this destructuring for..in thing it really caught my eye. I was not completely sure of what it mean, so I've done a couple of tests, and it's amazing, you can write code that elegant like this:


var ar = ["a", "b", "c"];
for (var [i,v] in ar){
print (i + ": " + v );
}

var ob = {
name: "Iyan",
age: 30
};
for (var [k,v] in ob){
print (k + ": " + v );
}


If you change "print" for "console.log" and try it in firebug you'll see that it works fine for objects (second sample) but not for arrays (first sample), which appears odd to me as this seems to be part of JavaScript 1.8 and modern versions of Firefox seem to implement it...

Update, 2012/11/25 With the functional style additions to ES5, both cases above can be easily rewritten with the new forEach method in the Array object:

var ar = ["a", "b", "c"];
ar.forEach(function(item, index){
console.log (index + ": " + item );
});
 
var ob = {
name: "Iyan",
age: 30
};
Object.keys(ob).forEach(function(key){
console.log(key + " : " + ob[key]);
});

No comments:

Post a Comment