Are global variables and variables in global scope different? Please see the code below or the JSfiddle implementation - http://jsfiddle.net/2ngj9rqa/.
a = 10;
var b = 20;
function x() {
a = 20;
}
alert(window.a);
alert(window.b);
Are global variables and variables in global scope different? Please see the code below or the JSfiddle implementation - http://jsfiddle.net/2ngj9rqa/.
a = 10;
var b = 20;
function x() {
a = 20;
}
alert(window.a);
alert(window.b);
that's a trick in JSFiddle, b
is wrapped in onload
but not window
if you choose no wrap
, it's fine. Also try the same in plunker is fine.
The code you've written will work fine in all major browsers.It won't work because it is wrapped by onload in jsfiddle.Both a and b are global variables here and both of them are in global scope. You can access them from anywhere in your code unless you introduce a variable with same name inside a function's own scope.There is something called variable scoping and hoisting.All the variables(except implicit global) are hoisted at the top of its scope when you declare a variable or assign value to it(with var keyword ofcourse) .know more on variable and function hoistingSo,your code is equivalent to this:
var b;
a = 10;
b = 20;
function x() {
a = 20;
}
alert(window.a);
alert(window.b);