JavaScript is a versatile and powerful programming language widely used for web development. However, its flexibility can sometimes lead to unintended errors and problematic behaviors in code. To address these issues, JavaScript introduced Strict Mode, a feature that helps developers write cleaner, more robust, and error-free code.
Strict Mode can be seen as a "strict" variant of JavaScript that eliminates some of the language's more problematic features. By enforcing stricter parsing and error handling, it encourages best practices and helps catch common coding mistakes at an earlier stage.
What is Strict Mode in JavaScript?
As the name suggests, Strict Mode enforces some strict principles for a Javascriptprogram; this means that the leverages given by JavaScript are not available while working in the strict mode.
Working in the Strict Mode means that you cannot get away by writing a bad syntax code. JavaScript will avoid simple syntax errors and execute the code flawlessly if you are not working in strict mode.
For instance, if you initialize a variable with some value without declaring the variable in the script, the JavaScript compiler will not throw an error and simply ignore it.
In other words, the machine understands that a human is not a machine, and it makes errors.
Caption: Wholesome robot girl
Source: Reddit
But if you want to make errors and learn from your mistakes like a true leader, then JavaScript Strict Mode is made for you.
JavaScript Strict Mode got introduced in ECMAScript version 5 (2009), along with it many other features like JSON support, String.trim() function, Array.isArray() function, Array iteration methods, etc. were also got added in ECMAScript version 5.
To use JavaScript Strict Mode in your programs, you just have to include one line at the top of your script.
"use strict";
// Rest of the program
You can use javascript strict mode in two ways- if you declare it at the top of the script, then it will be applied for the entire program, and if you declare this in a function body, then the scope of strict mode will be local meaning it will be applied to only the function.
function multiply(a, b){ m = a*b; return m; } console.log(multiply(10, 22));
As you can see in my index.js file, I have not declared the ‘m’ variable, which is a syntax fault.
Let’s see what output I get from this.
Caption: Console output without strict mode
In my console, why am I getting the correct result? Yes, you guessed it right!! It’s because the JavaScript compiler ignores these petty issues, so we don’t have to worry about it.
Now let’s see what happens when I use strict mode.
index.js
"use strict"; // working in strict mode functionmultiply(a, b){ m = a*b; return m; } console.log(multiply(10, 22));
Output:
Caption: Console output with strict mode
Now, Why am I getting an error that m is not defined? Yes, Exactly, you guessed it right again!! Since we are working in Strict Mode, JavaScript doesn’t ignore our errors and throws them on the console.
I’ll have to syntactically correct my code now (that is, declare m before using it)
index.js
"use strict"; // working in strict mode functionmultiply(a, b){ var m = a*b; return m; } console.log(multiply(10, 22));
This code will not give any error and prints 220 on the console.
I know you guys must be wondering that if the Strict Mode is so cruel and punishes us for making mistakes, why is it even there, and why do we have to include this in our programs.
Why do we need JavaScript Strict Mode?
We use strict mode in JavaScript because it identifies the silent errors that were earlier ignored and throws them on the console to correct our syntax. Ignoring such minor errors can give rise to significant mishaps in industry projects.
A code written in Strict Mode executes faster because the compiler doesn’t have to deal with minor errors.
Till now, we have seen how Strict Mode dealt with the undeclared variable. Now let’s explore more uses of Strict Mode.
Use-case of Strict Mode in JavaScript
1. Using JavaScript Strict Mod For undeclared variables
In the above example, weI have explained how the Strict Mode throws errors in the case of undeclared variables. So, you should always correctly declare all the variables in JavaScript before initialization.
2. Using JavaScript Strict Mod For undeclared objects
Since the objects are also variables in JavaScript, initializing an undeclared object is also syntactically wrong in JavaScript.
"use strict";
obj = {k1:100, k2:200, k3:300, k4:400};
This will throw an error that “obj is not defined.”
3. Using JavaScript Strict Mod For parameters with the same name in a function
If there are multiple parameters with the same name in a function, we’ll not get an error in the normal mode because the JavaScript compiler simply uses one of the parameters. But in Strict mode, it will give an error because it doesn’t know which parameter to use.
"use strict";
functionmultiply(a, a){
var m = a*a;
return m;
}
console.log(multiply(10, 22));
Here my function doesn’t understand which ‘a’ I want to square. Hence it will randomly give either 100 or 484 in normal mode, giving an error in Strict Mode.
4. Using JavaScript Strict Mod For deleting functions or objects
In JavaScript deleting an object or a function is prohibited. So in the strict mode, we should keep this mind that we cannot delete objects and functions in JavaScript.
"use strict";
functionmultiply(a, b){
var m = a*b;
return m;
}
let v = 0;
delete v; // Line 1
delete multiply; // Line 2
Line 1 or line 2 will throw an error “Delete of an unqualified identifier in strict mode” on the console.
5. Using JavaScript Strict Mod For undeletable properties
Apart from custom-defined objects and functions, many default functions and objects are undeletable like JavaScript Prototypes<LINK TO BLOG - Inheritance and The Prototype Chain in Javascript>.
"use strict";
deleteObject.prototype;
The above delete statement will throw an error saying that we “cannot delete property prototype of a function.”
6. Using JavaScript Strict Mod For keywords in JavaScript
Certain keywords cannot be used as variables in JavaScript, so if we accidentally name a variable that matches the name of some keyword, we’ll get an error message in the Strict Mode.
For example, the keyword ‘eval’ or ‘arguments’ cannot be used as variables.
"use strict";
leteval = 28;
letarguments = 28;
This will print an error “Unexpected eval or arguments in strict mode” on the JavaScript console. To check practice by yourself with the help of an online javascript compiler.
Prevents Silent Errors: Throws errors for assignments that would silently fail in non-strict mode.
Eliminates Global Variables: Reduces the chances of accidental global variable declarations.
Secures this Keyword: Ensures this is undefined in functions not called as methods.
Disallows Duplicate Parameters: Prevents defining functions with duplicate parameter names.
Improves Performance: Some JavaScript engines can optimize code better in strict mode.
Frequently Asked Questions
What is the syntax of declaring Strict Mode in JavaScript?
To use JavaScript Strict Mode, we can either include “use strict”; on the top for our script with a global scope or put “use strict”; at the top for our function with a local scope limited to the function body.
When was Strict Mode got introduced in JavaScript?
Strict mode came into play with the release of ECMAScript version 5 in 2009.
How to Disable Strict Mode in JavaScript
To disable Strict Mode, simply avoid including "use strict"; at the beginning of your script or function. If you want to revert to non-strict mode within a strict context, you can define a new function without the strict directive.
Is it Necessary to Use Strict Mode in JavaScript?
While it's not strictly necessary to use Strict Mode in JavaScript, it is highly recommended. It helps prevent common coding errors, encourages best practices, and enhances overall code quality, making it easier to maintain and debug applications.
Conclusion
In this article, we have discussed Strict Mode In JavaScript. Strict Mode in JavaScript is a valuable tool that enhances code quality and robustness by enforcing stricter parsing and error handling. By preventing silent errors, eliminating unintended global variables, and promoting best practices, Strict Mode helps developers create cleaner and more maintainable code. While not mandatory, adopting Strict Mode can significantly reduce the likelihood of bugs and improve performance in your applications.