0

I have been proved I do not truly understand javascript closure, and I am being confused by the following codes. I thought fxn would access the outside foo, but it actually print out "underfined". Why??

var foo = "hello";
function fxn(){
   alert(foo);
   var foo = "test"
}

fxn();
Daniel Shen
  • 2,986
  • 1
  • 14
  • 13

2 Answers2

6

This is because in JavaScript, variables get hoisted, which means

Variables are initialised to undefined when created. A variable with an Initialiser is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.(ES5 §12.2)

Thus, semantically, your code would be equivalent, to the following...

var foo = "hello";
function fxn(){
   var foo; //Variables are initialised to undefined when created
   alert(foo);
   foo = "test"; //A variable with an *Initialiser* is assigned the value of its *AssignmentExpression* when the *VariableStatement* is **executed**
}

fxn();
Moritz Roessler
  • 8,542
  • 26
  • 51
1

You define your variable foo outside your function. If you repeat calls for var, you redefine the variable inside the function and it loses its allocation.

Remove var in the function to access foo into the function fnx.

var foo = "hello";
function fxn(){
   alert(foo);
   foo = "test";
}

fxn();

Jsfiddle

R3tep
  • 12,512
  • 10
  • 48
  • 75
  • could you explain it a bit more? – Daniel Shen Feb 10 '14 at 12:53
  • 1
    You define your variable "foo" outside your function. If you repeat calls for "var", you redefine the variable inside the function and it loses its allocation. – R3tep Feb 10 '14 at 12:58
  • I would add to R3tep: 1) redefining the in method hides the external definition, but ... 2) you are using a variable before it is defined => 'undefined' (see also C5H8NNaO4 answer) – Hezi Feb 10 '14 at 13:02
  • @Hezi For me `foo` is a global variable on this example ([link](http://stackoverflow.com/questions/944273/how-to-declare-a-global-variable-in-a-js-file)). So the variable is defined and after `alert()` is updated. – R3tep Feb 10 '14 at 13:07
  • @R3tep Correct. But in the original question, the variable was redefined using 'var'. – Hezi Feb 10 '14 at 13:13
  • @Hezi _I thought fxn would access the outside foo, but it actually print out "underfined"_ Redefined using 'var' is an error for me in this question – R3tep Feb 10 '14 at 13:20