JS sharp vars

2009-11-27

So today I learned something new. Sharp variables in Javascript. I've actually never heard of this concept before, and yet Mozilla supports it since at least 2007. Ohwell. That's also a warning, this is proprietary stuff. Only works in Mozilla!

Ok so what happens when you do this:
Code:
var a = []; a.push(a);

You'll have an array that has one element, itself. There's a paradox in there somewhere.. ;) but no matter.

Now try to do this in one line. You can't. Because you can't make the temporary variable in the same expression. So here's how...

Code:
var a = #1=[#1#];

Now (a == a[0]) equals true.

The way this works is by temporary assignment and some sort of substitution. #1= is an assignment operator (no spaces allowed... "#1 =" is still a syntax error). You can use any alphanumeric (only numbers allowed...) character between # and =, and more than one. You can then later (still the same expression!) refer to that variable created through #=... by ##. This will insert the same reference as whatever you put in # when you defined it with the #= operator.

This might cause a little confusion with output, at first.

The output of

Code:
({a:#1=String("hi"),b:#1#,c:#1#}).toSource()

will be

Code:
({a:"hi", b:#1=function String() {[ native code ]}, c:#1#})

Now when I saw this the first time, I didn't quite understand why "b was different from c". That's because it's not. In fact, that's what Firefox is trying to tell me rather explicitly. It first tells you that #1# is defined as "function String() {[native code ]}" and assigned to b. Then it tells you that c has the same value as b. Not only does it have the same value, it's pointing to the exact same reference! There's an identity relation here. But it's all just output. When you compare b and c with == or === you'll see that they're equal.

You can only assign (explicit) objects this way, there's no casting or coercion going on (throws error).

I'd like to remind you again that this is Mozilla only. And it exists for at least two years. But I have a feeling that Mozilla's proposals have a better chance of becoming ECMA than other browservendors...

I personally think this is one of those features you'd best not mess with unless absolutely forced. You're better of taking the somewhat longer road (more characters) than using this feature. Unless you're obfuscating your code. It's perfect for that purpose...

Well, I hope it helps you. I sure think it's going to confuse the hell out of anyone having to read this crap secondhand :)