Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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.

  • + Share This
  • 🔖 Save To Your Account