ECMAScript 5 added Strict Mode to JavaScript. Many of you may have first seen mention of this if you’ve used JSLint. It helps to remember that JavaScript still behaves much like an interpreted vs. compiled language as each browser/parser makes assumptions to execute code faster in different manners.
There are four primary features/goals of strict mode:
- Throws errors for some common coding issues, that are sometimes obscure but previously didn’t throw an error.
- Prevents or throws errors for potentially “unsafe” actions (such as gaining access to the global object).
- Disables functions that are confusing or poorly thought out
- Potentially code in strict mode could run faster by eliminating mistakes that would make it difficult for JavaScript engines to perform optimizations
Initial support added in FireFox 4 and MSIE10:
WARNING: if you chose to do this at a ‘file’ level, be sure to never concatenate several files together that are not ALL strict.
JS File Example:
"use strict";
function testFunction(){
var testvar = 1;
return testvar;
}
// This causes a syntax error.
testvar = 2;
JS Function Example:
function testFunction(){
"use strict";
// This causes a syntax error.
testvar = 1;
return testvar;
}
testvar = 2;
REFERENCES: