Yes, you should always use var
.
Not using var
has two major drawbacks:
- Accessing a variable within a function that is not defined within that function will cause the interpreter to look up the scope chain for a variable with that name until either it find one or it gets to the global object (accessible in browsers via
window
) where it will create a property. This global property is now available everywhere, potentially causing confusion and hard-to-detect bugs;
- Accessing an undeclared variable will cause an error in ECMAScript 5 strict mode.
Also, not using var
for global variable is not exactly the same as using var
: when using var
, the property it creates on the global object has the internal DontDelete
attribute, which is not the case without var
:
// Next line works in any ECMAScript environment. In browsers, you can
// just use the window object.
var globalObj = (function() { return this; })();
var x = 1;
delete globalObj.x;
alert(x); // Alerts 1, x could not be deleted
y = 2;
delete globalObj.y;
alert(y); // Error, y is undefined