In this example, we have a function, within which we set a variable and then use some jQuery to modify a div. However, because we didn’t specify the “var” keyword, we’ve actually just added a new object to the global scope: message. In fact, if some other functionality was relying on the existence of a global object message, we just replaced it with ours, so that other part of the system is likely to break now, even though no part of it has changed. We’ve added tight coupling to our design, probably inadvertently, making our application more brittle and less maintainable.
Another option is to calculate the number of objects in the global space, and ensure you’re not adding to it. This can be done as part of your test suite on a per-function basis, asserting that each function begins and ends with no change in the global state (or, if the function intends to add to global state, ensuring it adds only what is expected). The key to this is being able to count how many objects are in global at a given time, which you can do using this code:
Now if you run this, you should see that the function ends with one more item in global scope than it starts with (the exact numbers will vary on the environment in which it runs).
Another option is to specify “use strict” which is done by simply adding this string to your code, either locally or globally, followed by a semicolon, like so:
Doing so will, among other things, prevent the use of undeclared variables, which is the source of the problem in the sayHello() function above. Strict mode is supported in Chrome 13+, IE 10+, Safari 5.1+, and Firefox 4+. If you add it to the code above (see this fiddle), you’ll get an error when you try to run the code (check the console in your developer tools):