JavaScript - strict mode

0 points
Created by:

In this article, we would like to explain what is strict mode in JavaScript.

1. Declaring

We declare strict mode with "use strict"; directive at the beginning of:

  • a function - so only code in the function will be executed in the strict mode¬†(local scope),
  • a script - so all the code¬†in the script will be executed¬†in the strict mode (global scope).

The "use strict" is a literal expression that tells JavaScript to execute code in a strict mode. It was presented in ES5 (ignored by earlier versions of JavaScript).

2. What strict mode does?

Here are some main functionalities of the strict mode:

  • it changes previously accepted "wrong¬†syntax" into¬†errors,
  • it doesn't allow¬†mistyping a variable name (which outside the strict mode creates a new global variable),
  • any assignment to a non-writable / getter-only / non-existing property or¬†non-existing variable/object¬†will throw an error,
  • this¬†keyword in functions behaves differently, it¬†refers to the object that called the function,
  • basically, strict mode makes it easier to write secure code in¬†JavaScript.

3. Things you can't do inside strict mode

  • use variable or object without declaring it,
  • delete¬†variable, object or function¬†(delete operator),
  • duplicate¬†parameter name,
  • use octal numeric literals,
  • use octal escape characters,
  • delete undeletable property (like e.g Array.prototype),
  • use eval¬†and arguments¬†keywords as the variable name,
  • use with statement.

4. Examples

Using a variable without declaring it:

  • without strict mode
    // ONLINE-RUNNER:browser;
    x = 10;  // No errors, we create new global variable
  • with strict mode
    // ONLINE-RUNNER:browser;
    "use strict";
    x = 10;  // In strict mode this causes an error

Using a variable without declaring it inside a function:

  • // ONLINE-RUNNER:browser;
    x = 10;  // This doesn't lead to an error
    function foo() {
      "use strict";
      y = 20;  // This leads to an error


Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā