Basic, Types

What Is the Purpose of "use strict" in JavaScript and What Are the Benefits of Using It?

February 13, 2023

use strict is a JavaScript syntax that instructs the execution environment to follow strict mode when running code. Under strict mode, JavaScript executes syntax in a stricter manner and will report errors for some non-compliant code. In this article, we will explore what use strict is, how it works, and what benefits it provides to JavaScript developers.

What is use strict?

Use strict is a statement in JavaScript that tells the interpreter to execute code in strict mode. When code is executed in strict mode, the interpreter will enforce stricter syntax rules and report errors for certain types of non-compliant code.

How to Use use strict

use strict can be used in two ways:

  1. At the top of a JavaScript file, which applies strict mode to the entire file:

    'use strict';
    // code here
  2. At the beginning of a function, which applies strict mode to that function only:

    function myStrictFunction() {
      "use strict";
      // code here will run in strict mode

Benefits of Using Strict Mode

The purpose of using strict mode is to improve the safety and readability of JavaScript code. By using strict mode, developers can better control the behavior of their code and avoid common errors.

Here are some examples of how strict mode can be used:

  • Prohibiting the use of undeclared variables:

    "use strict";
    x = 10;
    // Uncaught ReferenceError: x is not defined
  • Preventing the redefinition of variables:

    "use strict";
    function sum(a, a) {
      return a + a;
    // Uncaught SyntaxError: Duplicate parameter name not allowed in this context
  • Disallowing the deletion of non-deletable properties:

    "use strict";
    var y = 20;
    delete y;
    // Uncaught SyntaxError: Delete of an unqualified identifier in strict mode.
  • this value is undefined in the global scope:

    "use strict";
    console.log(this); // undefined

By adhering to stricter syntax rules, code written in strict mode is generally easier to read, debug, and maintain.

Related Articles