Consider the following snippet in javascript.
The output of the following snippet is :
The first alert shows "undefined" whereas the second alert shows "2"
var a = 1;
function test(){
alert(a);
var a = 2;
alert(a);
}
test();
Why does the first alert not show the value of the global variable a which is 1?
Answer
It is called "hoisting" in JavaScript. Your function is automatically transformed into this one:
var a = 1;
function test() {
var a;
alert(a);
a = 2;
alert(a);
}
test();
Nice read about that: http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/
No comments:
Post a Comment