Strict Mode is a new feature of ECMAScript 5, which allows you to place the entire program, or a certain function, in a "strict" operating context. This strict context will prevent certain operations and throw more exceptions.
Although ECMAScript 5 is backwards compatible with ECMAScript 3, in strict mode all features deprecated in ECMAScript 3 are disabled (or throw errors) instead of being compatible.
Enabling strict mode has the following benefits:
1. Catch some programming errors and throw exceptions.
2. Prevent some relatively "unsafe" operations (such as accessing global variables) and throw exceptions.
3. Disable some confusing features.
Most information about strict mode can be found on page 223 of the ES5 Specification [PDF].
(Note: ECMAScript 5’s strict mode is different from Firefox’s strict mode)
How to enable strict mode
Add this statement at the beginning of the program to enable strict mode for the entire script:
A practical application of enabling strict mode inside a function is to define the entire Javascript class library inside a strict mode function, so that it does not affect external code:
(function(){
"use strict";
// Define your library strictly...
})();
// Non-strict code...
Variables and Properties
Assignment to an undefined variable will fail instead of making the variable a global variable.
Writing a property with a writable property of false, deleting a property with a configurable property of false, or adding an extensible property with a false property will result in an error (these properties are pre-agreed). In the past, these operations did not throw an exception and simply failed silently.
Performing a delete operation on a variable, function or function parameter will cause an error.
delete foo; // Error
delete test; // Error
function test2(arg) {
delete arg; // Error
}
eval
Any use of the name "eval" (the main intention is to point the eval function to a variable or object property) is prohibited.
Function
Overriding the arguments object results in an error:
with() { } statement is completely broken in strict mode.