0

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);
RobG
  • 142,382
  • 31
  • 172
  • 209
Nikhil Pai
  • 127
  • 1
  • 7
  • This is because you've set JSFiddle to wrap your code in an `onload` handler -- change that to "No wrap" and it will work properly. – Qantas 94 Heavy Jan 01 '15 at 12:54
  • @GolezTrol actually `var b=20` will create a property on the global object too if the code is in the global context. – Ben Aston Jan 01 '15 at 14:21
  • I removed that comment. I think it's a misconception by an editor that this question was about jsFiddle specifically and as far as I can judge this question is just a duplicate of [What's the difference between a global var and a window.variable in javascript?](http://stackoverflow.com/questions/6349232/whats-the-difference-between-a-global-var-and-a-window-variable-in-javascript) – GolezTrol Jan 01 '15 at 16:46

2 Answers2

2

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.

hjl
  • 2,794
  • 3
  • 18
  • 26
1

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);
AL-zami
  • 8,902
  • 15
  • 71
  • 130
  • 1
    "*All the variables are hoisted at the top when you declare or assign value to a variable*", not not at all. Declared variables are created before any code is executed. Variables created by assignment (aka implicit globals) do not exist until the assignment that creates them is executed. Which means if the assignment is the last statement in the program, that's where the variable is created. – RobG Jan 01 '15 at 13:15