Question

Possible Duplicate:
Javascript scoping variables theory

Hi all,

I want to ask something stranger. Here is the code.

var a = "defined";
function f() {
   alert(a);
   var a = 5;
}
f();

alerts "undefined"

Can anyone explain that why I am getting "undefined".

Fatih..

Was it helpful?

Solution

That is called JavaScript Hoisting i suppose. Check out this video to learn more about it and solution to it:

http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/

To make it work, you will have to remove the var keyword form variable a:

var a = "defined";
function f() {
   alert(a);
   a = 5;
}
f();

So basically, it is a variable scope issue. The act of removing var keyword makes a variable globally available. Hence, there is no error raised this time.

OTHER TIPS

In the function you get a new scope.

The var a in the function declares a local variable a, which masks the global one.

The assignment to a takes place later (after the alert), so until then a is undefined.

The confusing part is that it does not matter if you have the var a declaration on top or anywhere else in the function (can even be inside an if). The effect is the same: It declares a variable for that scope (effective even for code that is located before the declaration). That is why jslint recommends to declare all local variables on top.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top