Thomas Fuchs
Hi, I'm Thomas Fuchs. I'm the author of Zepto.js, of script.aculo.us, and I'm a Ruby on Rails core alumnus. With Amy Hoy I'm building cheerful software, like Freckle Time Tracking and Every Time Zone and write books like Retinafy.me.
   Want me to speak at your conference? Contact me!

Learning by exploring

June 14th, 2011

To learn a language by heart, try to set some time aside to explore it! Set yourself a specific goal—for example, find three ways to convert a character code to a string in JavaScript.

Here’s the basic set up, with what probably makes the most sense in almost any situation.

var charCode = 65;
String.fromCharCode(charCode) // => "A"

Where to go from here? It seems, at first that there is no other way to achieve this, right? Wrong, of course.

As a scripting language, JavaScript has powerful ways to evaluate generated code. Let’s try using the eval function to do this. Remember that JavaScript strings can contain escape sequences, for example in the form of xAB, where AB is a hexadecimal character code:

eval("'\x"+charCode.toString(16)+"'") // => "A"

An here’s a third way to do it, using the unescape DOM method:

unescape('%'+charCode.toString(16)) // => "A"

There are even more possible ways to achieve this conversion—try to find one!