tags:

views:

93

answers:

3

I tried the following in JavaScript (Firefox 3.5, Windows XP):

(function(){
    window.foobar = 'Welcome!';
})();

var foobar = 'PWN3D!';

alert(foobar);

The output was 'PWN3D!'. Why did my code PWN me? I thought var name = value; executed first.

+2  A: 

I'm not sure what you mean by var statements being executed first. The code you have written looks to be working exactly as I would have expected:

  • An anonymous function is created
  • The anonymous function is executed, which sets foobar to "Welcome!"
  • The foobar variable is set to "PWN3D!"
  • An alert box is raised with the current value of foobar, "PWN3D!"
Adam Batkin
+1  A: 

Your alert statement sees the local variable, foobar and alerts its value as it is higher on the scope chain than window.foobar.

sworoc
(In this case, window.foobar and the local variable foobar happen to be the same thing since you are at the top level of execution.)Also, it will execute the anonymous function first, and then move on to the local variable assignment "PWN3D!", finishing with the alert which will output as you've seen, "PWN3D!".
sworoc
+9  A: 

From the specification (page 87):

A variable with an Initialiser is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.

So the var causes the variable to be created first, but the value ('PWN3D!') is assigned to it in the normal execution order.

David Dorward