The statement "use strict"; instructs the browser to use the Strict mode, which is a reduced and safer feature set of JavaScript.
List of features (non-exhaustive)
Disallows global variables. (Catches missing
vardeclarations and typos in variable names)Silent failing assignments will throw error in strict mode (assigning
NaN = 5;)Attempts to delete undeletable properties will throw (
delete Object.prototype)Requires all property names in an object literal to be unique (
var x = {x1: "1", x1: "2"})Function parameter names must be unique (
function sum (x, x) {...})Forbids octal syntax (
var x = 023;some devs assume wrongly that a preceding zero does nothing to change the number.)Forbids the
withkeywordevalin strict mode does not introduce new variablesForbids deleting plain names (
delete x;)Forbids binding or assignment of the names
evalandargumentsin any formStrict mode does not alias properties of the
argumentsobject with the formal parameters. (e.g. infunction sum (a,b) { return arguments[0] + b;}This works becausearguments[0]is bound toaand so on. ) (Seeexamplessection below to understand the difference)arguments.calleeis not supported
[Ref: Strict mode, Mozilla Developer Network]
Examples:
- Strict mode code doesn't alias properties of arguments objects created within it
function show( msg ){
msg = 42;
console.log( msg ); // msg === 42
console.log( arguments[0] ); // arguments === 42
}
show( "Hey" );
// In strict mode arguments[i] does not track the value of
// the corresponding named argument, nor does a named argument track the value in the corresponding arguments[i]
function showStrict( msg ){
"use strict";
msg = 42;
console.log( msg ); // msg === 42
console.log( arguments[0] ); // arguments === "Hey"
}
showStrict( "Hey" );