Pages

Saturday, August 21, 2010

λ as a variable name in JavaScript

JavaScript is a functional language, or at least has very functional roots we could all probably agree.

Functional languages are based on lambda calculus and the CS literature often uses examples where a lambda expression is called simply, "lambda."

In JavaScript, one common use of lambdas is when you register a callback function with some asynchronous operation like an ajax request. Another is for operations on collections of objects like visiting every item in an array.

I wondered if one could use the lambda character, λ, as a variable name in javascript. It would be more compact (one character instead of five six) and (more importantly) would look cool. Turns out you can do this!

See it run here.



Notice that the character encoding is set to UTF-16. If you don't do this you'll get errors. Since the encoding is set that way, I don't even use html entities like λ to write λ :)

Note: I haven't tried this in any version of IE but it appears to work in Chrome, Safari and Firefox.

Now, how do you actually type λ into a text editor? That took some digging. Here's what I did on OSX:

  1. Open System Preferences -> Language and Text -> Input Sources
  2. Scroll down to "Unicode Hex Input" and make sure that checkbox is checked.
  3. Open the US Flag (or nationality of your locale :) icon in the upper right of the OSX menu bar and switch to "Unicode Hex Input" (the "U+" icon)
  4. Now whenever I want a λ I can just hold down the Option key while I type 03bb and blammo I get a λ. Which by the way is still five key presses but looks way cooler than "lambda" and takes up less space on the screen.

I have no idea what you have to do on linux or windows.

You're right, this isn't very practical. And setting your encoding from UTF-8 to UTF-16 like, doubles the bytes you have to transmit. But you ARE gzipping all of your http responses aren't you? AREN'T YOU?