JavaScript - strict mode

0 points
Created by:
Dirask Community

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.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé