close
The Wayback Machine - https://web.archive.org/web/20241006042114/https://www.geeksforgeeks.org/strict-mode-javascript/
Open In App

Strict mode in JavaScript

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

The “use strict” directive, introduced in ECMAScript version 5, is a literal expression rather than a statement and is ignored by earlier JavaScript versions. Its purpose is to enforce strict mode, ensuring the code is executed with stricter parsing and error handling. In strict mode, you cannot use undeclared variables, among other enforced rules. Using “use strict”; eliminates silent errors, enhances performance, disables unsafe features, and makes code more secure and easier to debug.

The benefits of Using strict

Strict mode makes several changes to normal JavaScript semantics. 

  • Eliminates Silent Errors: Converts JavaScript silent errors into throw errors, making debugging easier.
  • Optimization: Helps JavaScript engines perform optimizations, potentially making strict mode code run faster than non-strict code.
  • Future-Proofing: Prohibits syntax likely to be defined in future ECMAScript versions.
  • Prevents Unsafe Actions: Throws errors when relatively “unsafe” actions are taken, such as accessing the global object.
  • Disables Confusing Features: Disables features that are confusing or poorly designed.
  • Security: Makes it easier to write “secure” JavaScript

How to Use Strict Mode

Strict mode can be used in two ways, remember strict mode doesn’t work with block statements enclosed in {} braces. 

  • Global Scope: Applies to the entire script.
  • Function Scope: Applies to individual functions.

Using Strict Mode for the Entire Script

To invoke strict mode for an entire script, put the exact statement “use strict”; (or ‘use strict’;) before any other statements. 

// Whole-script strict mode syntax
'use strict';
 let v = "strict mode script!";

Enable strict mode on a function-by-function basis to avoid issues when concatenating strict and non-strict scripts, ensuring compatibility and preventing unintended strict mode application in the entire script.

Using Strict Mode for a Function

Likewise, to invoke strict mode for a function, put the exact statement “use strict”; (or ‘use strict’;) in the function’s body before any other statements.

function strict() {

  // Function-level strict mode syntax
  'use strict';

  function nested() { return 'Javascript on GeeksforGeeks'; }

  return "strict mode function!  " + nested();
}
function notStrict() { return "non strict function"; }

Examples of using Strict mode

Example: 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: 

BERJAYA

Example: 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: 

BERJAYA

Example: 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: 

BERJAYA

Example: 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: 

BERJAYA

Example: 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: 

BERJAYA

Example: 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: 

BERJAYA

Example: Writing to a Read-Only Property

Using ‘use strict’; and defining obj.x as non-writable (writable:false) throws an error when attempting to assign 3.14 to obj.x, violating its non-writable property definition.

JavaScript
'use strict';
 let obj = {};
 Object.defineProperty(obj, "x", {value:0, writable:false});

 // Will throw an error
 obj.x = 3.14;    

Output: 

BERJAYA

Example: Writing to a Get-Only Property

Using ‘use strict’; disallows assigning values to read-only properties like obj.x with a getter, causing an error in the code trying to assign 3.14 to obj.x.

JavaScript
'use strict';
 let obj = {get x() {return 0} };

 // Will throw an error
 obj.x = 3.14;     

Output: 

BERJAYA

Example: Deleting an Undeletable Property

Using ‘use strict’; prohibits deleting properties of built-in objects like Object.prototype, which causes an error in the code snippet attempting to delete Object.prototype.

JavaScript
'use strict';

 // Will throw an error
 delete Object.prototype; 

Output: 

BERJAYA

Example: Using “eval” as a Variable

Using ‘use strict’; prevents using eval as a variable name, causing an error. The code snippet demonstrates this by attempting to assign a value to eval.

JavaScript
'use strict';

 // Will throw an error
 let eval = 3.14;  

Output: 

BERJAYA

Example: Using “arguments” as a Variable

Using ‘use strict’; disallows using arguments as a variable name, causing an error. The code snippet demonstrates this by attempting to assign a value to arguments.

JavaScript
'use strict';

 // Will throw an error
 let arguments = 3.14;    

Output: 

BERJAYA

Example: The with Statement

Using ‘use strict’; prevents with statements, causing an error if used. The code snippet demonstrates this by attempting a with statement, which throws an error.

JavaScript
'use strict';

 // Will throw an error
 with (Math){x = cos(2)}; 

Output: 

BERJAYA

Note: In function calls like f(), this value was the global object. In strict mode, it is now undefined. In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.

Conclusion

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.



Previous Article
Next Article

Similar Reads

Strict vs Non-strict Mode in JavaScript
JavaScript is a widely used programming language that allows developers to create dynamic and interactive web applications. It has two modes of operation: strict mode and non-strict mode. These modes affect how JavaScript code is executed, and understanding the differences between them is crucial for writing secure and reliable code. Strict mode is
4 min read
JavaScript Strict Mode
JavaScript is a dynamic language i.e. to elaborate, each Javascript component is dynamic starting from variables to the code itself. With the help of JavaScript, you can create variables in the runtime, change it's data-type, create new functions or replace existing logic. In other words, while using JavaScript the developer is in almost full contr
4 min read
What is Strict Mode and how to enable it in JavaScript ?
The strict mode of JavaScript, introduced in ECMAScript 5, is a mechanism to opt into a restricted version of JavaScript." Strict mode modifies the regular JavaScript semantics in the following ways: Some JavaScript silent errors are eliminated by converting them to throw errors. How to enable strict mode in JavaScript: Use "use strict" in front of
3 min read
JavaScript SyntaxError – Octal literals are not allowed in strict mode
If you put an octal literal in a code block that runs on strict, the result may be SyntaxError: Octal literals are not allowed in strict mode, since they can lead to unintended actions and confusion, numbers such as 0123 should never be strictly used, to understand this error better including possible causes, consider these examples. Understanding
3 min read
What is JavaScript Strict mode and how can we enable it ?
JavaScript is a forgiving language as it ignores developers' or programmers' silly mistakes or errors in code like termination of the statement, variable declaration, the wrong data type of variable, hoisting issues, and many more. Sometimes these errors give unusual results which difficult for programmers or developers to find an error in long cod
5 min read
New Features of strict Mode in React 18
React 18 introduces significant enhancements, especially in strict mode, aimed at improving development experiences. It offers comprehensive warnings to catch common mistakes early, along with improved component stack traces for easier debugging. These enhancements emphasize early error detection and smoother debugging processes, contributing to a
6 min read
Difference between standards mode and quirks mode
Standards mode and Quirks mode are two modes introduced by web browsers to treat new standards-compliance sites differently from old legacy sites. At present, there are three modes used by the layout engines of web browsers to work along: quirks mode, almost standards mode, and full standards mode. The document type declaration of HTML, also known
3 min read
JavaScript SyntaxError - "use strict" not allowed in function with non-simple parameters
This JavaScript exception 'use strict' not allowed in function occurs if strict modes 'use strict' statement is used at the beginning of a function with default parameters, rest parameters, or destructuring parameters. Message: Edge: Cannot apply strict mode on functions with non-simple parameter list Firefox: SyntaxError: "use strict" not allowed
1 min read
Strict Equality(===) Comparison Operator in JavaScript
JavaScript Strict Equality Operator is used to compare two operands and return true if both the value and type of operands are the same. Since type conversion is not done, so even if the value stored in operands is the same but their type is different the operation will return false. Syntax: a===b Example 1: In this example, we will compare the val
2 min read
Strict Inequality(!==) Comparison Operator in JavaScript
JavaScript Strict Inequality Operator is used to compare two operators and return true if they both are unequal. It is the opposite of the Strict Equality operator but like the Strict Equality Operator, it also does not perform type conversion. Syntax: a!==b Example 1: In this example, we will use the inequality operator on the same data types. C/C
1 min read
What are the Benefits of Using the use strict Directive in JavaScript ?
The "use strict" directive enables strict mode in JavaScript, which provides several benefits: Strict mode eliminates some JavaScript silent errors by changing them to throw errors.Strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical co
1 min read
Difference between Transitional and Strict doctype
In this article, we are going to see the difference between Transitional and Strict doctype. Transitional and Strict both are the kinds of doctypes available in HTML 4. Now, what doctype is? A doctype declaration or document type declaration is information to the browser about what document type should it expect. It is not an HTML tag. All the HTML
4 min read
HTTP headers | Strict-Transport-Security
HTTP Strict Transport Security (HSTS) is a web security policy mechanism that helps protect websites from malicious activities and informs user agents and web browsers how to handle its connection through a response header. Whenever a website connects through HTTP and then redirects to HTTPS, an opportunity for a man-in-the-middle attack is created
2 min read
How to enforce strict null checks in TypeScript ?
In Typescript to enforce strict null checks in tsconfig.json file, we need to enable "strictNullChecks" to true. When "strictNullChecks" is false, the language generally ignores variables of type null and undefined. If null and undefined is used in places where a definite value is expected, it raises an error. When "strictNullChecks" is true when n
2 min read
Explain HTTP Strict Transport Security
HTTP stands for Hypertext Transfer Protocol. This protocol is used for communication in web requests. HTTPS on the other hand stands for Hypertext Transfer Protocol Secure. While HTTP doesn't concerned about encrypting data that is getting transmitted in HTTP Requests and is generally prone to Man-In-The-Middle (MiTM) attacks. An adversary in the n
3 min read
How Object.is() method differ from strict equality (===) ?
Object.is():The Object.is() method is used to compare two values for equality.It returns true if the values are the same, and false otherwise.It handles special cases such as -0 and NaN differently compared to strict equality (===).Specifically, Object.is() distinguishes between +0 and -0, and between different NaN values.Example: Below is an examp
1 min read
How to Enable HTTP Strict Transport Security (HSTS) for Apache?
HTTP Strict Transport Security (HSTS) is a security policy component that assists with safeguarding sites against protocol for downsize attacks and cookies highjacking by forcing the HTTPS connections. Using HSTS on your Apache web server improves the security of your site. PrerequisitesAccess: Admin access to your Apache web server.SSL/TLS Certifi
5 min read
Less.js Options Strict Units
Less stands for Leaner Style Sheets is a CSS preprocessor and is a backward-compatible language extension for CSS. Less provides many features such as variables, in the development, it is common to see the same value repeated again and again so in this case variables help to reuse the code and provide more such options to make it easy to handle the
3 min read
Find the Mode in a Binary Search Tree using JavaScript
One can find the mode in a binary search tree using JavaScript. The mode in the binary search tree will be the value of the node that occurs with the highest frequency among all the nodes in the tree. If there is more than one mode present in the binary search tree then return all modes present in the array. There are several approaches to calculat
3 min read
Design a Navigation Bar with Toggle Dark Mode in HTML CSS & JavaScript
One can create a navigation bar with a toggle switch for dark mode using HTML, CSS, and JavaScript. If we use the dark mode effect in our website then it can attract user attention and users can use our website in any situation. With the help of JavaScript, we'll implement the functionality to toggle between light and dark modes. Approach:At first
6 min read
Creating a Dark Mode for Websites using HTML Bootstrap & JavaScript
Dark Mode for websites enhances user experience by providing a visually comfortable environment, especially in low-light conditions. Implemented with HTML, Bootstrap, and JavaScript, it offers a sleek interface that reduces eye strain and promotes readability, offering users greater accessibility. Prerequisites HTMLBootstrapJavaScriptApproachHere w
3 min read
How to Create Dark/Light Mode for Website using JavaScript/jQuery?
Creating Dark/Light Mode for a website involves toggling between light and dark color schemes. This feature allows users to switch between the two schemes based on their preferences. JavaScript/jQuery is utilized to dynamically adjust CSS styles, enhancing accessibility and user experience according to user or system settings. Steps to Create Dark/
2 min read
Find Mode of an Array using JavaScript
To find the mode in an array with JavaScript, where the mode is the number occurring most frequently. Various approaches can be employed to find the mode, and an array may have multiple modes if multiple numbers occur with the same highest frequency. Example:Input:3, 6, 4, 6, 3, 6, 6, 7 , 6, 3 , 3Output:6 , 3Use the below approaches to Find Mode in
4 min read
Light/Dark Mode User Profile Card using HTML CSS and JavaScript
This article will show how to make an Animated User Profile Card using HTML, CSS, and JavaScript. We generally see these effects in portfolios of professionals. In this, we have created a code that generates a personalized card with the user's name, image, and description. Additionally, we've implemented a hover function that resizes the card when
3 min read
Build a responsive Burger Website with Toggle Dark Mode in Tailwind CSS & JavaScript
Burger Website is easy to use and designed with Tailwind CSS and JavaScript. It adjusts smoothly to different screens and has a dark mode option. It's perfect for veggie burger lovers, making it easy to browse and order anytime, anywhere. With Tailwind CSS for styling and JavaScript for interactivity, it provides a fun experience. PrerequisitesTail
10 min read
How to Make Dark Mode for Websites using HTML CSS & JavaScript ?
Dark mode (or night mode) is a popular design feature where the background is dark, and the text and icons are light. It reduces eye strain in low-light conditions and can help save battery life on some devices. In this article, we’ll explain how to easily add dark mode to your website using HTML, CSS, and JavaScript. Steps to Add Dark Mode to Your
3 min read
How to enable dark mode in Tailwind CSS ?
In this article, we will see how to enable dark mode in Tailwind CSS. there are many ways, some of them we will see. Tailwind CSS has special features to enable dark mode on the webpage. To enable dark mode in Tailwind CSS, we can define a dark theme in our Tailwind config file section and then we have to use the dark class in our HTML to apply it
3 min read
Tailwind CSS Mix Blend Mode
This class accepts lots of value in Tailwind CSS in which all the properties are covered in class form. This class is used to specify how an element’s content should be blended with the background. In CSS, we can do that by using the CSS mix-blend-mode property. Mix Blend Mode classes : mix-blend-normal: No blending is applied to the element.mix-bl
3 min read
Prevent System from Entering Sleep mode in ElectronJS
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. In some desktop applications, a need arises due to
6 min read
Node.js stats.mode Property from fs.Stats Class
The stats.mode property is an inbuilt application programming interface of the fs.Stats class which is used to get the file type and mode as bit-field. Syntax: stats.mode; Return Value: It returns a number or BigInt value that represents a bit-field that describes the file type and mode. Below examples illustrate the use of stats.mode in Node.js: E
2 min read