jskatas.org Continuously Learn JavaScript. Your Way.

Strict mode: Turn strict mode on/off

The use strict directive indicates that the code should be executed in "strict mode", where you can for example not use undeclared variables.

Turn strict mode on/off explicitly (in ES5)

WHEN (global) code starts with "use strict" THEN strict mode is turned on for the whole file/module
//: {"jskatas": {"runnerOptions": {"runGivenCodeOnly": true}}} 'use strict'; undefinedVar = 1; // This throws in strict mode!
WHEN eval code starts with "use strict" THEN the executed code is run in strict mode
//: {"jskatas": {"runnerOptions": {"strictMode": false}}} // NOTE: The `with` statement is forbidden in strict mode. const invalidInStrictMode = 'without () {}'; assert.throws(() => eval(` 'use strict'; ${invalidInStrictMode} `), { name: 'SyntaxError', message: /strict mode/i, });
WHEN a function starts with "use strict" THEN the code inside of it is run in strict mode
//: {"jskatas": {"runnerOptions": {"strictMode": false}}} assert.throws(function() { 'use not-strict'; undefinedVar = 1; // This throws in strict mode! } , ReferenceError);
WHEN the code passed to new Function() starts with "use strict" THEN the code is run in strict mode
//: {"jskatas": {"runnerOptions": {"strictMode": false}}} const codeThatThrowsInStrictMode = 'var undefinedVar = 1'; // Undefined vars throw in strict mode! assert.throws(new Function(`'use strict'; ${codeThatThrowsInStrictMode}`), ReferenceError);

Links

The MDN docs about strict mode.
Chapter 4.2.2 in the specification explains that and why ECMAScript offers a "strict mode" to restrict language features, and that it can coexist with non-strict code in the same program.
Chapter 10.1.1 in the specification explains how to turn strict mode on and off.
Appendix C "The strict mode restriction and exceptions" explains the differences between strict mode and non-strict mode in detail.

Required Knowledge

Related Katas

Strict mode

  • Turn strict mode on/off

Difficulty Level

ADVANCED

First Published

16 October 2023

Stats

4 tests to solve