Understanding Variable Instantiation

Quick, just from examining this code (no fair testing it), what will the following alert?

var f = 1;
function f() { }

alert(f);

The fact that I consider this code intersesting (or at least instructive) may tip you to what the answer will be: it's 1. Surprised? If you are you're likely suffering from the common misconception that your JavaScript code is executed in the order you wrote it. If that were true the variable named f would first be declared, then assigned the value 1. Next the function named f would be declared, replacing that existing f and finally the alert would show us the function. But we know that's not what happens.

What really happens is explained in section 10.1.3 of the ECMAScript specification, entitled "Variable Instantiation". If you imagine there is a Variable Object and the JavaScript engine is adding properties to it based on your source code, the specification defines the following distinct steps and the order in which they must happen:

  • Function declarations
  • Variable declarations
  • The rest

Note that when you write var f = 1; you are really doing two things together: declaring a variable named f and then assigning the value of 1 to it. So, putting all that together, effectively the code in our previous example is the same as this:

function f() { } // function declarations first
var f;           // variable declarations next
f = 1;           // the rest
alert(f);

contact

tags

archive

more blogs