Strict Mode
strict mode
is a way to opt in to a restricted variant of JavaScript, this was introduced in ECMAscript 5. To use strict mode
just place 'use strict';
before any statements or with in a function.
Some Key Changes
Makes debugging easier by highlighting/throwing errors for common mistakes/typos.
Prevents accidental globals.
// Assuming a global variable mistypedVariable exists mistypedVaraible = 17; // this line throws a ReferenceError due to the // mispelling of variable
Throws error deletion of undeletable properties.
"use strict"; delete Object.prototype; // throws a TypeError
Disallows duplicate property names or parameter values.
"use strict"; //property name var o = { p: 1, p: 2 }; // !!! syntax error //Parameter name function sum(a, a, c){ // !!! syntax error "use strict"; return a + b + c; // wrong if this code ran }
Makes eval() safer. Variables and functions declared inside of an eval() statement are not created in the containing scope, strict mode also forbids deleting plain names.
"use strict"; eval("var x; delete x;"); // !!! syntax error
For more reading see: