I realize that omitting the var keyword when declaring a variable inside a function is bad because it will declare the variable as a global variable, not with function-level scope.
However, what if you're declaring a global variable? Other than a style preference, is there any reason to do
var myvar=0;
versus
myvar=0;
?
I personally would prefer the former.
Here's a snippet that I wrote that intentionally clobbers global variables, with the var it's clobbered from the get go, without the var it's only clobbered after you set it (in IE11 and FF) in Chrome the hoisting doesn't seem to be happening and the variable isn't initially clobbered:
<html>
<title>test javascript variable scope</title>
<script>
//var innerHeight = undefined; //declare it here, because it gets hoisted...
function showlength() {
//length is a global object, so this function is aware of it...
alert('showlength says its ' + length);
}
function showIH() {
//length is a global object, so this function is aware of it...
alert('showIH says its ' + innerHeight);
}
//alert('attach your debugger now');
//debugger;
alert('show the original value of length, it is ' + length);
showlength();
length = "abc";
alert('the length is ' + length);
showlength();
alert('the window.length has been clobbered, it is ' + window.length);
alert('innerHeight is ' + innerHeight);
showIH();
alert('window.innerHeight is clobbered because the initialization has been hoisted, here it is ' + window.innerHeight);
var innerHeight; //it doesn't matter if you declare it here, or up above...
innerHeight = innerHeight = "xyz";
showIH();
alert('innerHeight is ' + innerHeight);
alert('window.innerHeight is ' + window.innerHeight);
</script>
<head>
</head>
<body>
<p>Test some variables here</p>
</body>
</html>