Wednesday, July 25, 2012

Notes from "Javascript: The Good Parts"

Some time ago I read JavaScript: The Good Parts, a nice book on Javascript, the lingua franca of the web. Book concentrates on the nice features of Javascript and warns of the not-so-nice features.

My experience with web frontend technologies isn't too strong so I was pretty happy with the book.


This post is a short summary of things that I wasn't too familiar with, mostly in order I encountered them:

Misc things:

  • Javascript has only one numeric type, the same as Java's Double
    • Which means that 1 ends up being 1.0, no separate integers
    • Floating point with computers effects checking of equality, 0.1+0.2==0.3 ends up as false 
  • Javascript has function scope (no block scope)
  • Javascript objects are class-free mutable keyed collections
  • Inheritance : Javascript is a prototypal language
    • Objects inherit straight from other objects
    • prototype objects (e.g. Cat.prototype)
    • Note that this prototype relationship is dynamic.
  • Important widely used convention : constructions functions with capital letter, others with minor
  • A bonus one (not from the book) : For some time I wondered why some variables are started with $ and some not. Seems to be convention to name variables holding jQuery objects to start with a $. See for example Why would a javascript variable start with a dollar sign (at Stack overflow)

The invocation patterns (a.k.a what is 'this')

Method invocation pattern

  • When the function is a property of an object, it is called a method. When the function is called as a method of an object, this points to the object.

Function invocation pattern

  • When the function isn't called as an method, it is invoked as a function -> this points to the global object
  • A mistake in the language design.
  • Causes problems with inner function inside an outer function (inner function doesn't share this of the outer function
    • A common workaround is to save this of outer function to a variable named that.

Constructor invocation pattern

  • According to the writer of the book, "worst of two world" (classical vs. prototypal inheritance)
  • If a function is invoked with the new prefix, a new object will be created with a prototype link and this points to that new object.
  • Functions intended to be called with new are called constructors. They should be given a capitalized name!

Apply invocation pattern

  • Functions can have methods; apply method of a function lets us to choose the value of this, before the arguments.
For those interested, Yehuda Katz has a good summary of these : Understanding Javascript function invocation.