Open In App

“use strict” in JavaScript

Last Updated : 03 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In JavaScript, “use strict” is a directive that enables strict mode, which was first introduced in ECMAScript 5 (ES5) to assist in the writing of safer and more error-free code. “Use strict” is used to indicate that the code should be executed in strict mode, applying a stricter set of rules for JavaScript coding.

What is “use strict” in JavaScript?

The “use strict” is the literal expression that enables strict mode for JavaScript. It is added at the top of a JavaScript file, function, or block, and tells the JavaScript engine to run the code in strict mode. In other words, this mode brings in a stricter set of rules for writing JavaScript with more warnings and throwing more errors.

Syntax: To enable strict mode, simply add “use strict”; at the top of a script or function:

"use strict";
console.log("Strict mode is enabled");

function myFunction() {
    "use strict";
    let x = 3.14;
    console.log(x);
}

Why to use Strict Mode?

Strict mode was introduced to address some of JavaScript’s problematic features and encourage developers to write safer, more optimized code. Here are some reasons why strict mode is beneficial:

  • Avoids Accidental Global Variables: In normal JavaScript, if you assign a value to a variable that has not been declared, it creates a global variable. Strict mode throws an error instead, preventing such accidental global variables.
"use strict";
x = 10; // Throws an error because 'x' is not declared
  • Eliminates Silent Errors: In non-strict mode, some operations fail silently (e.g., assigning a value to a non-writable property). Strict mode makes these operations throw errors, helping developers catch bugs early.
"use strict";
Object.defineProperty(this, "PI", { value: 3.14159, writable: false });
PI = 3.14; // Throws an error
  • Disallows Duplicates in Function Parameters: In strict mode, using the same name for multiple parameters in a function is not allowed, which prevents confusion.
"use strict";
function sum(a, a, c) { 
    // Syntax error in strict mode
    return a + a + c;
}
  • Prevents this from Defaulting to the Global Object: In normal JavaScript functions, this defaults to the global object (window in browsers) when the function is called without an explicit receiver. Strict mode changes this behavior by setting this to undefined in such cases, improving security and preventing unintended side effects.
"use strict";
function showThis() {

// Logs 'undefined' instead of the global object console.log(this); } showThis();
  • Avoids Deletion of Non-Deletable Properties: In non-strict mode, deleting an undeletable property has no effect, while strict mode throws an error.
"use strict";
delete Object.prototype; // Throws an error in strict mode

How to use “use strict” Mode?

Strict mode can be enabled in two main ways: for the entire script or for individual functions.

  • Global Strict Mode: Place “use strict”; at the top of your JavaScript file to apply strict mode globally across the entire script.
"use strict";
// All code in this file runs in strict mode
let name = "Sourav";
  • Local Strict Mode (Per Function): To enable strict mode for a specific function, add “use strict”; inside the function definition.
function display() {
    "use strict";
    // Code inside this function runs in strict mode
    let message = "Hello, World!";
    console.log(message);
}
// Code outside this function runs in normal mode

1. Mistyping a Variable Name

In strict mode, assigning a value (3.14) to an undeclared variable (x) without prior declaration throws an error.

JavaScript
// Using a variable, without declaring it, is not allowed:
'use strict';
 x = 3.14;  // will throw an error

Output

use-strict-javascript

Mistyping a Variable Name

2. Using a Variable Without Declaring It

In strict mode, assigning a value to an undeclared variable (x) as an object ({p1:10, p2:20}) without prior declaration throws an error.

JavaScript
// Objects are variables too.
// Using an object, without declaring it, is not allowed:
'use strict';

// Will throw an error
x = { p1: 10, p2: 20 }; 

Output

use-strict-javascript

Using a Variable Without Declaring It

3. Deleting a Variable or Object

In strict mode, attempting to delete a variable (delete x;) or function (delete x; where x is a function) declaration throws an error.

JavaScript
'use strict';
 let x = 3.14;

// Deleting a function is also not allowed
'use strict';
 function x(p1, p2) {}; 

 // Will throw an error
 delete x;      

Output

javascript-strict-mode

Deleting a Variable or Object

4. Duplicating a Parameter Name

Using ‘use strict’;, defining a function with duplicate parameter names (p1, p1) causes an error due to parameter name duplication being disallowed in strict mode functions

JavaScript
'use strict';

 // Will throw an error
 function x(p1, p1) {};   

Output

strict-mode-javascript

Duplicating a Parameter Name

5. Octal Numeric Literals

Here we Using ‘use strict’;, 010 is interpreted as an invalid octal literal because octal literals (starting with 0) are not allowed in strict mode, causing an error when assigning to variable x.

JavaScript
'use strict';

 // Will throw an error
 let x = 010;       

Output

octal-use-strict

Octal Numeric Literals

6. Escape Characters

Here we Using ‘use strict’;, \010 is interpreted as an invalid octal literal, causing an error when trying to assign it to variable x.

JavaScript
'use strict';

 // Will throw an error
 let x = \010;     

Output

escape-use-strict

Escape Characters “use strict”

Limitations and Compatibility Considerations

Strict mode is generally compatible with modern JavaScript, but there are some points to keep in mind:

  • Not Retroactive: Adding “use strict”; does not affect previously executed code.
  • Old Browsers: In very old browsers that do not support strict mode, the directive is simply ignored, making it backward compatible.
  • Module Scripts: In ES6 modules, strict mode is enabled by default, and you do not need to add “use strict”;.

When Not to Use Strict Mode?

In certain cases, enabling strict mode may not be appropriate:

  • Working with Third-Party Code: If you’re using third-party libraries that were not built with strict mode in mind, enabling strict mode may introduce errors.
  • Quick Prototyping: For rapid prototyping, enabling strict mode might slow you down by enforcing rules.

Strict mode in JavaScript, introduced in ECMAScript version 5, enforces stricter parsing and error handling. It eliminates silent errors, enhances performance, disables unsafe features, and future-proofs code. Using “use strict” ensures more secure, optimized, and debuggable JavaScript code.



Next Article

Similar Reads

three90RightbarBannerImg
  翻译: