Tuesday 1 January 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...