Sunday, 29 January 2017

Javascript local and global variable confusion

In Javascript, the variable declarations are automatically moved to the top of the function. So, the interpreter would make it look more like this:




var myname = "initial"
function c(){
var myname;
// alerts undefined
alert(myname);
myname = "changed";
// alerts changed
alert(myname);
}
c();



This is called 'hoisting'.


Due to hoisting and the fact that the scope for any variable is the function it's declared in, it's standard practice to list all variables at the top of a function to avoid this confusion.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...