Wednesday 20 May 2009

Handle global variables in JavaScript

When people write decent JavaScript (read: when they use JavaScript frameworks like jQuery which handle the quirks of JavaScript for them) they will often assume that certain top level variables are there, without explicitly defining it.

e.g.: $("#test").html("test");

This line is assuming that jQuery has been loaded and that the $ object is defined. If jQuery isn't loaded, the code will fail and claim that $ is undefined. Because of this, the JSLint validator will complain when validating this code and will state the following:

Implied global: $ 1
Problem at line 1 character 1: '$' is not defined.

(Note that this will also happen when we call a function that hasn't been defined yet inside a function. Sometimes it's impossible to avoid this.)

This can and should be fixed by adding this to the top of the document:

/*global $ */

Inside this global statement we can define all of the top level variables we expect there to be. This will tell JSLint that it should assume those variables are defined (or will be defined in time), and it will no longer complain. It also a very nice way of documenting which files and frameworks we need to run a certain JavaScript file, so it's a win-win again.

No comments:

Post a Comment