Note: Turns out this only works in Firefox since it is the only browser to include versions of JavaScript beyond 1.5. Perhaps something will show up in ECMAScript N/Harmony/whatever.


Alright, JavaScript is pretty cool. There are plenty of “tricks” that still boggle my mind. I just found another cool trick in Mardak code (he would do this…).

This is about multiple assignment in JS. Well, it’s actually about destructuring assignment, but potato, potato.

Hopefully by now we all know that it can be done with arrays.

var arr = ["yea, yea", "we knew this worked"];
var [a, b] = arr;
// a == "yea, yea"
// b == "we knew this worked"
view raw assignment_array.js hosted with ❤ by GitHub

What I didn’t know is that it can also be done using objects.

var obj = {
foo: "WTF",
bar: "this works?",
baz: "looks like it"
};
var { foo: c, bar: d} = obj;
// c == "WTF"
// d == "this works?"
view raw assignment_object.js hosted with ❤ by GitHub

This mostly makes sense now that I know it works, I was just a bit surprised. The syntax is strange, but it’s oddly satisfying (and follows from the assignment from an array).

Turns out this works for nested objects too…

var obj2 = {
foo: { dude: "WTF" },
bar: "this works too?",
baz: "looks like it"
};
var { foo: e, bar: f} = obj2;
// e == { dude: "WTF" }
// d == "this works too?"

Just keep in mind the same rules for object references applies. If I change obj2.foo.dude, that changes e.dude

And last but not least, we can also access values directly with nested objects.

// using the unchanged obj2 from above...
var { foo: { dude: g } } = obj2;
// g == "WTF"

Modifying obj2.foo.dude here will have no effect on g.

Add this to the list of cool things that have been implemented in JS 1.6, 1.7, and 1.8, but yet still aren’t available in all browsers (sigh). Generators, Iterators, array comprehensions, block scoping with let… all cool things that are used regularly within the Firefox codebase.