The statement "use strict";
turns on "strict mode" when it's the first statement in a file or function.
It only applies to the file for function it's present in.
"use strict"
is actually an expression (a literal string), not a statement. This allows it
to be used regardless of the version of JavaScript used: it will be ignored in older versions.
It is used at the beginning of a file or the beginning of a function.
Strict mode and "use strict";
are actually from ES5 but it's important to mention.
In strict mode, certain parts of JS behave differently.
-
converts some mistakes into errors. The most important example is a typo in a variable name:
"use strict"; var numbers; // non-strict mode: silently create new global var // strict mode: throws ReferenceError nubmers = [1, 3, 6, 34, 765];
Also, object keys and function parameter names must be unique in strict mode.
-
prohibits the
with
statement. (What's that? A feature poorly-designed enough to get prohibited) -
eval()
'd code gets its own scope for variables, won't leak vars (for security) -
can't delete variables:
var x; delete x;
(but you can still delete object properties:delete obj.x
) -
this
will be undefined if called without athis
(either byobj.method()
syntax or bound withbind
,apply
orcall
), instead of defaultingthis
to the global object, which is insecure and error-prone. -
no
arguments.callee
,arguments.caller
,fun.caller
,fun.arguments
(insecure and/or slow with dubious use-cases) -
added new reserved keywords, some of which are now used, some not (
let
was a reserved keyword before, now it has a meaning)_