In an HTML <script>
tag, outside of any function, does var
have any meaning?
Is there any difference between these three notations?
<script>
var a = 1;
b = 1;
window.c = 1;
</script>
In an HTML <script>
tag, outside of any function, does var
have any meaning?
Is there any difference between these three notations?
<script>
var a = 1;
b = 1;
window.c = 1;
</script>
At the top level (outside all functions) var
declares a global variable.
To avert this, wrap your code in a function.
(function () {
var a = 1;
}());
'a' in window;
// => false
Despite that each form declares a global variable, they have subtle differences. var
creates an undeletable property on window
, and is subject to typical hoisting rules whereby the property will exist on window
at the start of the var
statement's execution context. The other forms create a deletable property on window
at the time that the line of code is executed.
See this answer for more info.
In your simple, unlikely example, there is no difference, but there are a few subtle differences that can result in hair-pulling if you decide to make a habit of not declaring variables "since they are the same."
You can read up on these differences at the Mozilla Developer Network, my go-to on questions like this.
Summarizing briefly the main reasons b = 1
is bad:
Browsers in strict mode will throw an exception on b = 1
.
From within a function, only var a = 1
will be scoped to the function. It will be unclear whether you intend for b = 1
to be global or not. If you're mutating that variable, one day you're going to wonder why the heck you're getting different results from the same exact function with the exact same parameters.