The case of the “missing” VAR

A couple of days back a colleague (JS enthusiast) of mine asked me if it really matters to declare variables before use in JavaScript. He went on to say that he didn’t seem to find any side effects in doing so. Though I did tell him it has deep consequences (in terms of these rogue variables inheriting the global scope), I wanted him to appreciate this by experiencing it (and hence asked him to try this out) and in case he is still trying to figure it out, here’s a leading light for him and for many others who might still end up treading this path tomorrow…

If you end up in this situation (using a variable implicitly without declaration) in a global scope, this doesn’t have an impact (though not recommended) and I presume this is the situation this colleague of mine is in and hence didn’t notice any side effects whereas if you have a variable implicitly declared inside a function – that is, if it appears on the left side of an assignment expression but has not been declared with var – it is created as a global variableThis is because, in the process of looking up the variable in the scope chain, if the variable is not found all the way till the global scope, it is created at this point in global scope.

See the code below to understand the fun (I am sure this would have been a nightmare for many others):

function increment(x) {
	factor = x;//Implicit usage without declaration
	return function (y) {
		console.log(factor + y);
	};
}
var increment1 = increment(1),
	increment2 = increment(2),
	increment3 = increment(3);
increment1(1);//What result do you expect here?

You can see that in place of 2, you would be getting the result as 4 (for reasons already explained above). Now this is definitely something you wouldn’t want and you end up cursing the language for its unpredictability in addition to all the “undefined” errors it has to put up with (little knowing that it’s actually you who went rogue by not following some best practices and let some bad parts in the language get the best of its good parts).

The good thing is there is vaccine available that can help prevent you from not contracting this disease and those would be:

  1. JSLint/JSHint your code.
  2. The “use strict” Directive (starting ECMAScript version 5).

Happy Coding!

Advertisements