Wednesday, September 03, 2008

Javascript Revisisted

When starting an expedition with a new language, (most) people take time to fully understand and learn it before attempting to program with it. Except with Javascript... almost universally, it invites people to dive in without really knowing it. I'm paraphrasing Douglas Crockford here.

I've found this to be very true. Almost 10 years back I started playing around with html and then CSS. The natural final progression led me to Javascript. I clearly remember going through Thau's Javascript tutorials over at WebMonkey trying to actually figure out what I was hacking. Those were exciting times at the height of the "Browser War" with the DOM coming into its own: MS introducing document.all and Netscape's document.layers. After IE won, nothing much happened for the next 5 years. And Javascript, already considered a toy language back then was more or less ignored.

With the emergence of Ajax all that changed. People actually started taking a serious look at JS. Rahul found a series of videos - The Javascript Programming Language - by the above mentioned Douglas Crockford over at YUI threatre. They are by far the best material on revealing the real javascript and what a wonderful dynamic language it is. It is simple, yet, deceptively powerful. I took notes and here are some language highlights:

Overview
  • A real language - small, so easily approachable.

  • Dynamic - "load and go"... i.e. interpreted + loosely typed.

  • Objects are containers... i.e. HashMaps.

  • Prototypical inheritance - No classes. Inherit directly from objects.

  • Lambda support - Closures. "First lambda language to go mainstream".

Types
  • Numbers - 64-bit floats. NaN is result of erroneous operations.

  • Strings - 16-bit chars. Immutable. == compares string values.

  • null - nothing.

  • undefined - default variable value. Missing object members.

  • Booleans - falsy: false, null, undefined, empty string, 0, NaN. truthy:!(falsy)

  • Objects - everything else. Including functions.

  • Loosely typed != Untyped. Checks at runtime. Any type can be stored in any variable including functions.

Ops
  • == and != do type coersion. Use === and !== instead.

  • && and || return values.

  • foreach (i in object) iterates over ALL properties. Use hasOwnProperty check.

  • Scope - blocks {} don't have scope. Only functions have scope. Variables inside function are not visible outside.

Objects
  • Inherit from other objects.

  • Are an unordered Map.

  • Object literals: {} (Basis of JSON: simple data exchange format)

  • New empty object: new Object() == {} == object(Object.prototype)

  • New members are added by simple assignment. No need for a new class.

  • "Linkage" to "parent" object - Simple inheritance.

  • When setting values, only affects current object. When getting values, access goes "up", if not found in current object.

  • Pass by ref.

  • === is comparison on reference.

  • Remove member: delete object[name]

Arrays
  • Inherit from Object.

  • Indexes are strings (numbers are converted).

  • Array literals: [] (== new Array())

  • delete array[index] leaves a "hole" (value is undefined). Use Array.prototype.splice instead.

Functions
  • Are objects.

  • Inherit from Object and can store name/value pairs!

  • JS function == other language lambda.

  • function foo() {} is equivalent to var foo = function() {}

  • Can have inner functions with access to parent function scope even after parent function is invoked: Closures.

Misc
  • Can augment built-in types by modifying prototypes.

  • Avoid type wrappers (added to be similar to Java).

  • Browser 'window' is global object. Container for all global vars and built-in objects.

  • Every object is a separate namespace.

  • Browser apps are all single threaded.

DOM
  • id - uniquely identifies element.

  • Avoid document.all. Use document.getElementById(id), document.getElementsByName(name), .getElementsByTagName(tagName).

  • Document Tree Structure: document is root. document.documentElement is HTML tag. document.body is BODY tag.

  • Node: child, sibling, parent pointers. childNodes list.

  • Style: node.className/node.style.styleName

  • Events: Browser - event driven, single threaded, async programming model. Events targeted at particular nodes. Events cause invocation of event handlers. (Remove event handlers from nodes before deleting). node["on" + type] = function to add event handler. Event handlers send optional event object. Events bubble up from "specific" to "general".

  • Dialogs: alert, confirm, prompt all block async model. Avoid them in ajaxy apps.


Detailed slides:
The Javascript Programming Langauge
Advanced Javascript
DOM