Skip to content Skip to sidebar Skip to footer

Window Vs Var To Declare Variable

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

Solution 1:

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.


Solution 2:

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

Solution 3:

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.


Solution 4:

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


Solution 5:

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.


Post a Comment for "Window Vs Var To Declare Variable"