Tuesday, January 1, 2019

global scope and local scope in javascript




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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...