- 3.1 Declaring Functions
- 3.2 Higher-Order Functions
- 3.3 Function Literals
- 3.4 Arrow Functions
- 3.5 Functional Array Processing
- 3.6 Closures
- 3.7 Hard Objects
- 3.8 Strict Mode
- 3.9 Testing Argument Types
- 3.10 Supplying More or Fewer Arguments
- 3.11 Default Arguments
- 3.12 Rest Parameters and the Spread Operator
- 3.13 Simulating Named Arguments with Destructuring
- 3.14 Hoisting
- 3.15 Throwing Exceptions
- 3.16 Catching Exceptions
- 3.17 The finally Clause
- Exercises
3.8 Strict Mode
As you have seen, JavaScript has its share of unusual features, some of which have proven to be poorly suited for large-scale software development. Strict mode outlaws some of these features. You should always use strict mode.
To enable strict mode, place the line
'use strict'
as the first non-comment line in your file. (Double quotes instead of single quotes are OK, as is a semicolon.)
If you want to force strict mode in the Node.js REPL, start it with
node --use-strict
You can apply strict mode to individual functions:
function strictInASeaOfSloppy() { 'use strict' . . . }
There is no good reason to use per-function strict mode with modern code. Apply strict mode to the entire file.
Finally, strict mode is enabled inside classes (see Chapter 4) and ECMAScript modules (see Chapter 10).
For the record, here are the key features of strict mode:
Assigning a value to a previously undeclared variable is an error and does not create a global variable. You must use let, const, or var for all variable declarations.
You cannot assign a new value to a read-only global property such as NaN or undefined. (Sadly, you can still declare local variables that shadow them.)
Functions can only be declared at the top level of a script or function, not in a nested block.
The delete operator cannot be applied to “unqualified identifiers.” For example, delete parseInt is a syntax error. Trying to delete a property that is not “configurable” (such as delete 'Hello'.length) causes a runtime error.
You cannot have duplicate function parameters (function average(x, x)). Of course, you never wanted those, but they are legal in the “sloppy” (non-strict) mode.
You cannot use octal literals with a 0 prefix: 010 is a syntax error, not an octal 10 (which is 8 in decimal). If you want octal, use 0o10.
The with statement (which is not discussed in this book) is prohibited.