Thread:Mathmagician/@comment-3508190-20120504092551/@comment-3508190-20120504202411

You really should watch that screencast about "Evented Programming"! JavaScript is all about events. In JavaScript you don't have a synchronous program that starts at the beginning and ends at the end. JavaScript is asynchronous. The user may click somewhere... or type something in somewhere else... or resize the window... or all of that and more or less and in no particular order.

But it's not just user events: Page components load asynchronously as well e.g. In the youtube-example above the code calls an external source without having any idea when it will load - if at all. And so it passes a callback function to $.get that will be executed when (and if) its time comes and no sooner than that.

Fortunately functions are first class citizens in JavaScript. They can be passed as parameters and assigned to variables. Functions are OBJECTS in JavaScript. Or to put it differently: Everything is a function in JavaScript. That's what makes it such a joy to do event-driven programming in JavaScript.

Here's another example of functions as objects:

The kicker in this example is that the variable c outlives the function in which it is declared, because the inc- and log-methods still use it. That is called a closure. Closures are the high Zen of JavaScript. If When you grok closures, you grok JavaScript.