Strictly Javascript

There comes a time with a large Javascript project where having the code behave more like a 'usual' programming language becomes useful.  This is where 'strict mode' comes in.

Javascript is very forgiving.  Take the following:

myMsg = "Hiya";

No problem.  Yet programming from other languages will throw their arms in horror - The Variable has not been declared! We have a variable without declaring it with the var keyword.  If you want to enforce the use of the var keyword, to for example keep track of scope, then you can add the following:

'use strict'
myMsg = "Hiya";

The above will throw an error.  However if we amend the code to:

'use strict'
var myMsg;
myMsg = "Hiya";

This will be valid as the variable has been properly declared with var.

JS Fiddle

Scope

You can limit the 'strictness' to a function by declaring 'use strict' inside a function so that the strict rules only apply to that function ie:

function showMsg(){
    // only strict in the function
    'use strict'
    var myMsg1 = "local stuff"; 
    return myMsg1;
}

JS Fiddle

Beyond the declaration of variables strict mode will also add restrictions such as:

  • Preventing writing to read only properties
  • Stopping the extension of non-extensible objects
  • Preventing the duplication of object literal properties
  • Preventing the use of 'future' reserved words such as a 'public', 'static' and 'private'

For more information see MSN on Strict Mode