0

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>
Eric
  • 2,861
  • 6
  • 28
  • 59
  • Please see http://stackoverflow.com/a/1471738/637889 – andyb May 22 '14 at 21:00
  • I'd avoid variables in favour of using an IIEF to create a closure with the variable just inside that function. The variable can then be shared among the functions without using globals. – Quentin May 22 '14 at 21:00
  • Omitting the var keyword in non-strict mode _does not_ create a variable. It creates a plain-old property on the global object. It is equivalent to `globalThis.variableName = 'foo'`. – Ben Aston Apr 13 '20 at 18:02

1 Answers1

3

If you are using strict mode, which you should be, you need var to declare the variable. Assigning a value to an undeclared variable causes a reference error (such as trying to read an undeclared variable does outside of strict mode).

jnthnjns
  • 8,962
  • 4
  • 42
  • 65
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335