Javascript for n00bs

Recently a friend asked me for an easy way to learn JavaScript. I can’t remember how I learned myself, but I do remember some things that were surprising coming from other languages, or that I had guessed wrong or took me a while to understand for whatever reason, despite not really being complicated at all.

As I wrote the list for her anyway, I figured it could be useful for other people, too, so here it goes, somewhat edited:

  • It’s object-oriented, but it doesn’t have classes (instead, it’s prototype-based). The Java-like syntax often makes you think it’s a normal object-oriented language, but it’s not.

  • What are called “objects” in Javascript are hashes, really. It just happens that the values for some of the keys are functions. Related: object.prop and object['prop'] are equivalent.

  • The for (x in obj) { ... } statement is strictly an object (not an array) thing. If you need to traverse an array with a “for” loop, you have to use the C-style form: for (var i = 0, len = obj.length; i < len; i++) { ... }.

  • There are no methods in the sense of other programming languages. When you do object.blah(...) in JS, you’re simply calling the blah function with the “context” (ie. the value of the reserved word “this”) set. For example, you could do var f = obj.blah; f(...). That would (a) be perfectly legal, and (b) set “this” inside that function call to be undefined, not obj. The “call” function allows you to set that binding explicitly, like so: f.call(obj, ...).

  • This implies something that I find ugly: if you have two levels of functions, you need to save the value of the this of the outer function in some variable if you want to use it in the inner function. See example below:

  • JavaScript has functional language features: functions are first class citizens, and higher-order functions are possible and even common.

  • You should use the operators === and !== instead of == and != (the latter are too liberal with type casting).

  • You should get used to always using semicolon at the end. Although the interpreter adds them in most cases, in some other cases it might be a big surprise.

  • Also, JavaScript is full of small design problems and quirks. Learn them, learn how to avoid them, and you use tools like “jshint” or “jslint”. That way it’s much easier to enjoy the language :-)

  • Maybe I’m weird, but I have always found programming “inside” the browser to be awkward and clunky. To fool around with the language, you might want to use Node instead.

Example of two levels of functions:

// Imagine this function is a method
function foo(widgetList) {
    // Save the value of "this" for later
    var that = this;
    widgetList.forEach(function() {
        // Here, "this" points to widgetList. If we need
        // the object the "foo" method was called on, we
        // need to refer to "that", saved above
    }, widgetList);

Resources (that I haven’t read myself, but seem useful):