Languages
[Edit]
EN

JavaScript - strict mode

0 points
Created by:
Jacob
492

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
    console.log(x);
  • with strict mode
    // ONLINE-RUNNER:browser;
    "use strict";
    x = 10;  // In strict mode this causes an error
    console.log(x);

Using a variable without declaring it inside a function:

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

References

Alternative titles

  1. JavaScript "use strict"
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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.

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

Join