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?
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.
If you declare a variable, without using "var", the variable always becomes GLOBAL.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With