15

Possible Duplicate:
Difference between using var and not using var in JavaScript
Should I use window.variable or var?

I have seen two ways to declare a class in javascript.

like

window.ABC = ....

or

var ABC = ....

Is there any difference in terms of using the class/ variable?

Community
  • 1
  • 1
William Sham
  • 12,849
  • 11
  • 50
  • 67

5 Answers5

22

window.ABC scopes the ABC variable to window scope (effectively global.)

var ABC scopes the ABC variable to whatever function the ABC variable resides in.

gn22
  • 2,076
  • 12
  • 15
  • if I declare window.var outside all the functions i.e. in the script but not in any function, then that will also create a global variable. So, is in this case is there any difference between window.var and var?? – shivamag00 Apr 25 '20 at 06:56
10

var creates a variable for the current scope. So if you do it in a function, it won't be accessible outside of it.

function foo() {
    var a = "bar";
    window.b = "bar";
}

foo();
alert(typeof a); //undefined
alert(typeof b); //string
alert(this == window); //true
Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
4
window.ABC = "abc"; //Visible outside the function
var ABC = "abc"; // Not visible outside the function.

If you are outside of a function declaring variables, they are equivalent.

Dennis
  • 32,200
  • 11
  • 64
  • 79
3

window makes the variable global to the window. Unless you have a reason for doing otherwise, declare variables with var.

wanovak
  • 6,117
  • 25
  • 32
2

The major difference is that your data is now attached to the window object instead of just existing in memory. Otherwise, it is the same.

Tejs
  • 40,736
  • 10
  • 68
  • 86