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?

1
  • There are no classes in JavaScript. You are just declaring a variable. Please provide some more information. Aug 16, 2011 at 18:11

5 Answers 5

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.

1
  • 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, 2020 at 6: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
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.

3

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.