About Me

I'm just someone struggling against my own inertia to be creative. My current favorite book is "Oh the places you'll go" by Dr. Seuss

Thursday, August 6, 2009

Another javascript pitfall: Hoisting

The problem is that, whether you realise it or not, javascript invisibly moves all the var declarations to the top of the function scope.

so if you have a function like this


var i = 5
function testvar () {
alert(i);
var i=3;
}
testvar();


the alert window will contain undefined. because internally, it's been changed into this:


var i = 5
function testvar () {
var i;
alert(i);
i=3;
}
testvar();

this is called "hoisting". The reason Crockford so strongly advocates var declarations go at the top, is that it makes the code visibly match what it's going to do, instead of allowing invisible and unexpected behavior to occur. function definitions are also hoisted to the top of the scope.

Putting a var inside an if statement is not against "the rules" of the language, but it means that, because of var hoisting, that var will be defined regardless of whether the if statement's condition is satisfied. Javascript also does not have block scope, so declaring a variable inside a block is doubly confusing to those who come from languages that do have block scope, because of hoisting.

Keep in mind also that hoisting does not include the assignment, so the var declarations will be moved to the top, and left undefined until they're assigned later, as in the example above.

This is a feature that must have seemed like a good idea at the time, but it has turned out to be more confusing than helpful.

Sunday, August 2, 2009

Insomniac Theater, A dream

I had a dream about a particular cinema. Not one that I know if in the waking world, but one that I visited quite avidly in this dream world.

At this theater, you could purchase a ticket to see a contemporary movie at around 11:30pm at the regular price. Then, you could stay at the theater on until 6am, and watch classic/old/public domain movies and cartoons for free.

The theater would recoup the cost of this through sales at the snacks counter. This might actually work, sleep deprivation can make people quite hungry.