If you’re in the global scope, there’s not much difference. Read Kangax’s answer for explanation
If you are in a function, then var
will create a local variable, “without var” will look up the scope chain until it finds the variable or reaches the global scope (at which point it will create it)
There is a difference .
var x = 1
declares variable x
in the current scope (aka execution context). If the declaration appears in a function – a local variable is declared; if it is in the global scope – a global variable is declared.
x = 1
on the other hand, it’s just an attribute assignment. It first tries to resolve the x
scope chain. If it finds it anywhere in that scope chain, it does the assignment; if it doesn’t find x
, then it just creates the property on the global object (which is the top-level object in the scope chain) . x
Now, notice that it doesn’t declare a global variable, it creates a global property.
The difference between the two is subtle and can be confusing unless you understand that variable declarations also create properties (only on variable objects) and Javascript
…
The post javascript What is the difference between declaring variables with and without var first appeared on Lenix Blog .
This article is reprinted from https://blog.p2hp.com/archives/9814
This site is for inclusion only, and the copyright belongs to the original author.