Friday 16 December 2016

Variable: local scope, global scope or is it the JavaScript engine?



Here is something interesting I found while learning scope in javascript.



Code



var foo = "This is a global variable.";

var bar = function() {
alert(foo);
foo = "Value has been modified";
}

bar();
alert(foo);


This gives the normal response you think you would get, but if I change this one line:



from:



foo = "Value has been modified";


to:



var foo = "Value has been modified";


I get a value of undefined for foo, why is this? Since the function is global scope how come it doesn't accept the var keyword in front of it?



Edit



Now I understand basically what is happening the var foo in the function bar will gain most importance because of the var keyword and get hoisted up, but it will be hoisted up without the value it has been assigned.


Answer



In a var statement, there are two parts to it - the actual declaration:



var foo //;


... and the assignment, which is optional:



= 1234567890;


If there is no assignment done to it, the variable (if not already defined) defaults to undefined.






The variable declaration part is moved to the top of the current scope (the start of the function), but not the actual assignment (so it's equivalent to the following):



var foo = "This is a global variable.";

var bar = function() {
var foo; // undefined
alert(foo); // yes, it's undefined
foo = "Value has been modified"; // modify local, not global
}

bar();
alert(foo); // the global one


Functions create their own scope - for example take this:



var test = function ()
{ var bar = 1;
console.log(bar); // 1
};
test();
console.log(bar); // ReferenceError: bar is not defined

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...