Tuesday, August 23, 2011

JavaScript Strict Mode

Many of us have been taught that global variables are evil.  They contribute to code which is difficult to maintain.  The JavaScript language, however, allows global variables and they are quite common.  Luckily JavaScript has a lesser known mode called “strict mode” which will throw an error if we try to create a global variable.

To use strict mode you begin your script files with “use strict”; The quotes are needed also.  This will make all code inside this JavaScript file run under strict mode.  Any functions called from within this file will also run in strict mode.  Here is a quick example of code that allows global variables because it is not in strict mode.  And here is the same code which throws an error when trying to create a global variable. 

Strict mode tightens down a few other language features, most of which you won’t/shouldn’t care about anyway.  For instance normally you can have a function with this signature:

  function sum(x, x){};

Why you would want two parameters to have the same name, or how you would expect the code to work… I don’t know.  But strict mode throws an error if you try.  I consider that a good thing. 

For more info check out the MDN page about strict mode.