Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Window vs Var to declare variable [duplicate]

Tags:

javascript

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?

like image 453
William Sham Avatar asked Aug 16 '11 18:08

William Sham


People also ask

Is it necessary to use var keyword while declaring variable?

Variables can be declared and initialize without the var keyword. However, a value must be assigned to a variable declared without the var keyword. The variables declared without the var keyword becomes global variables, irrespective of where they are declared.

What happens if we declare a variable * without * the VAR let keyword?

If you declare a variable, without using "var", the variable always becomes GLOBAL.

Can we declare same variable in two times?

It is okay to declare variables with same name in different functions. Show activity on this post. Variables declared inside a function only exist in the scope of that function, so having the same variable name across different functions will not break anything.

What is the difference between window and global?

The global object provides variables and functions that are available anywhere. By default, those that are built into the language or the environment. In a browser it is named window , for Node. js it is global , for other environments it may have another name.


3 Answers

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.

like image 90
gn22 Avatar answered Oct 13 '22 19:10

gn22


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
like image 40
Alex Turpin Avatar answered Oct 13 '22 21:10

Alex Turpin


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.

like image 25
Dennis Avatar answered Oct 13 '22 19:10

Dennis