JavaScript Statement: strict mode and the
“use strict” directive
[this page | pdf | back links]
The "use strict" statement (more
precisely a ‘directive’ or literal expression) indicates the relevant part of
the code should be executed in “strict mode”. In strict mode, for example, you
cannot use undeclared variables. It was introduced in ECMAScript 2015.
Strict mode is declared
by adding "use strict"
to the beginning of the script or function to which it applies:
-
If it is declared at the beginning of a script it has global scope (i.e.
applies to all code in the script
-
If it is declared inside a function (at its start) then it has local
scope (i.e. applies only to code inside the function
Its syntax is designed to
be compatible with older versions of JavaScript. Compiling a numerical literal
(e.g. 1+2) or a string literal "hello" simply compiles to a
non-existent variable, so has no practical impact, so an ‘assignment’ like "use strict" is in effect
ignored by older versions of JavaScript.
The main advantage of
strict mode is that it makes it easier to write fault-free JavaScript, since it
makes it easier to pick up errors that are the result of otherwise bad syntax. Actions
that are not allowed in strict mode include:
-
Using a variable without declaring it
-
Using an object without declaring it
-
Deleting a variable, object or function
-
Duplicating a parameter name
-
Octal numeric literals and Octal escape characters
-
Writing to a read-only property
-
Writing to a get-only property
-
Deleting an undeletable property
-
Using the with statement
-
Using eval() to create
variables in the scope from which it is called
ECMAScript 2015 also
prohibited a range of keywords, some then still to be finalised, from being
used as variable names including e.g.: argument,
eval , implements, interface,
let, package, private,
protected, public, static,
yield
The this keyword also behaves differently
in strict mode. The this keyword
refers to the object that called the function. If this object is not specified
then in strict mode this will return undefined, whilst in normal (i.e. not
strict) mode it will return the global object (i.e. the window).
Code within classes is
automatically deemed to be written in strict mode.
NAVIGATION LINKS
Contents | Prev | Next | JavaScript Reserved Words