r/javascript • u/actionscripted • Aug 14 '09
Bet you didn't know you could do this in JavaScript
Here's how you create and assign multiple variables in a single line in JavaScript -- sort of like what you might do in Perl or other languages.
The magic follows the "var" assignment, the rest is just to setup the show.
function returnSomeStuff() {
return ['Hello', 'World'];
};
/*
* Bet you didn't know you could assign
* variables like this
*/
var [foo, bar] = returnSomeStuff();
alert([foo, bar].join(' '));EDIT: Does not work in WebKit browers.
15
u/Sephr Aug 14 '09 edited Aug 14 '09
This is JavaScript 1.7 destructuring. Bet you didn't know you could do this with object destructuring (it makes making functions that accept options objects much easier):
function foo([a, b], {c:d, e}) {
return a+b+d+e;
}
foo([1, 2], {"c":3, "e":4}) === 10;Real-world example:
function Person(
{
gender, name:[firstName, lastName, middleName], age,
billing:{creditcard:[cardType, cardNumber], shippingAddress}
}
) {
// no need to parse options, handle them here
}Btw, no "JavaScript" engines other than SpiderMonkey and Rhino actually run JavaScript. All other "JavaScript" engines run ECMAScript, which is different (though Opera does support limited array destructuring assignment stuff like [a, b] = [b, a]).
7
1
Aug 14 '09
I tried this in chrome and it gave a syntax error, it should be equivolent
var [asdf,asdf2] = (function(){ return [1,2];})();
1
u/actionscripted Aug 14 '09
Yeah...I only checked in Firefox 3.5.2. Doesn't seem to work in WebKit browsers like Chrome or Safari.
Not sure if this should be considered a bug in Firefox or a bug in Webkit. Anyone know a bit more about ECMAScript that can chime in?
7
u/realstevejobs Aug 14 '09 edited Aug 14 '09
This is destructuring assignment, which was introduced in JavaScript 1.7 along with array comprehensions, generators, and other cool features. That means it will work in Firefox 2+.
https://developer.mozilla.org/en/New_in_JavaScript_1.7
edit:formatting
2
Aug 14 '09
Anyone know if/when webkit will support newer versions of JavaScript?
2
u/itsnotlupus beep boop Aug 14 '09
When it becomes a ratified ecmascript standard, most likely.
Ecmascript 4 died a painful death, but Ecmascript 5 looks on track. It probably doesn't have any of the features you're thinking about, but at least they've agreed to update the spec, so who knows what'll happen after that.
2
u/masklinn Aug 14 '09 edited Aug 14 '09
The 1.x where x>5, never. It supports some array methods of 1.6 natively (though not the generics I think), js 1.6, 1.7 and 1.8 are basically proprietary Mozilla extensions to the standard. So they might support some part if it's useful for them, but overall it's unlikely you'll ever see let expressions in Webkit or Opera.
2
u/masklinn Aug 14 '09
Not sure if this should be considered a bug in Firefox or a bug in Webkit.
It's a proprietary extension to Javascript. So it's neither.
2
1
u/qwerty_0_o Aug 14 '09
Another thing I didn't know you could do in JS
var x = (function(){return 1})();
x = 1? too lazy to try/
3
u/actionscripted Aug 14 '09 edited Aug 14 '09
Yes, that'll work. You're wrapping a function inside of an anonymous one and calling it.
You can carry that trickery even further and create your own (slow) crazy loop constructs:
var str = "hello world"; // starting small... for (var i = 0; (str[i] != 'd'); i++) { alert(str[i]); } // and now we've gone off the deep end for (var i = 0; ((function(letter) { alert(letter); return (str[i]) ? ((letter == 'd') ? false : true) : false; })(str[i])); i++) { }4
u/gfixler Aug 14 '09
I used to go crazy-go-nuts with this kind of thing in Flash Actionscript, which, like most Javascripts was really ECMAScript (and thus it would usually work out in a browser as well). I would make anonymous functions inside of arrays that used values in other parts of the arrays in which they were declared, and that's just the beginning. It was all just for the science. I was a wild man. The world was mine.
2
u/palparepa Aug 14 '09
That declares an anonymous function that returns 1, then calls it and assigns the returned value (1) to x.
2
u/sgoguen Aug 17 '09
That's nice, but useless if you want to target 99% of browsers.
All in all, it seems like a really poor cheap knock-off to a really nice pattern matching system that you would find in something like ML or Haskell.
1
u/philogb Aug 20 '09 edited Aug 20 '09
I agree. I always thought it would be nice to have like a "let" expression for assigning stuff to variables with pattern matching. something like:
let [foo, bar, _] = returnSomeStuff();
or even
let { 'somekey': value, _ } = returnSomeStuff();
alert(value);
There's even function pattern matching that can be done in JavaScript. This should work:
/xyz/.test(function() {xyz;}); //true
So why not just add this thing?
I know Firefox has the let keyword taken for defining variables with block scope (instead of the less proper function scope 'var' has).
EDIT: should have read the comment below. This concept could be pushed further I think.
1
u/sgoguen Aug 20 '09
I pretty much don't have much hope for JavaScript for becoming a really good language. Instead, I'm hoping the next wave of programming languages will focus on compiling and targeting existing languages and runtimes.
This isn't new, as LISP programmers have been doing this for decades. However, it's nice to see this type of reflection finding its way into languages like C#, which supports reflection for expressions and enables you to write C# code that can be translated into SQL (LINQ to SQL).
0
-1
8
u/masklinn Aug 14 '09 edited Aug 14 '09
Or Opera, or Internet Explorer, …
In fact, it's simpler to say in which browsers it does work: browsers running on gecko 1.8.1 or superior (Firefox 2.0, Netscape 9, Seamonkey 1.1, Flock 1.0, Songbird 0.5, K-Meleon 1.1, Camino 1.6.5)