Using Strict Mode
This article describes using "strict mode" in JavaScript programs. Strict mode helps developers to avoid errors and write cleaner code. For example, an undeclared variable will cause an error in strict mode. Note that not all browsers support this functionality.
Strict mode applies to entire scripts or to individual functions. It doesn't apply to block statements enclosed in {}
braces; attempting to apply it to such contexts does nothing. eval
code, Function
code,
event handler attributes, strings passed to setTimeout()
, and related functions are entire scripts, and invoking strict mode in them works as expected.
Strict mode for scripts
To invoke strict mode for an entire script, put the exact statement "use strict";
(or 'use strict';
) before any other statements.
// Whole-script strict mode syntax 'use strict'; var v = "Hi! I'm a strict mode script!";
This syntax has a trap that has already bitten a major site: it isn't possible to blindly concatenate conflicting scripts. Consider concatenating a strict mode script with a non-strict mode script: the entire concatenation looks strict! The inverse is also true: non-strict plus strict looks non-strict. Obviously, concatenation of scripts is never ideal, but if you must, consider enabling strict on a function-by-function basis.
You can also take the approach of wrapping the entire contents of a script in a function and having that outer function use strict mode. This eliminates the concatenation problem and it means that you have to explicitly export any shared variables out of the function scope.
Strict mode for functions
Likewise, to invoke strict mode for a function, put the exact statement "use strict";
(or 'use strict';
) in the function's body before any other statements.
function strict() { // Function-level strict mode syntax 'use strict'; function nested() { return 'And so am I!'; } return "Hi! I'm a strict mode function! " + nested(); } function notStrict() { return "I'm not strict."; }
Strict mode for modules
ECMAScript 2015 introduced JavaScript modules and therefore a 3rd way to enter strict mode. The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
function strict() { // because this is a module, I'm strict by default } export default strict;
Strict mode for classes
All parts of ECMAScript classes are strict mode code, including both class declarations and class expressions – and so also including all parts of class bodies.