Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is the difference between "strict" and "non-strict" modes of JavaScript?
The "use strict" is a directive introduced in JavaScript 1.8.5 that enables strict mode execution. In strict mode, JavaScript enforces stricter parsing and error handling, while non-strict mode (the default) is more permissive and allows certain problematic practices.
Enabling Strict Mode
To enable strict mode, add "use strict"; at the beginning of your script or function. For global scope, place it at the top of the script file.
<!DOCTYPE html>
<html>
<body>
<p>Check the console for errors (F12)</p>
<script>
"use strict";
try {
a = 1; // This will throw an error
} catch (error) {
console.log("Error:", error.message);
}
</script>
</body>
</html>
Error: a is not defined
Key Differences
Undeclared Variables
// Non-strict mode (permissive)
function nonStrictExample() {
x = 10; // Creates global variable automatically
console.log("Non-strict: x =", x);
}
// Strict mode (throws error)
function strictExample() {
"use strict";
try {
y = 20; // ReferenceError
} catch (error) {
console.log("Strict mode error:", error.message);
}
}
nonStrictExample();
strictExample();
Non-strict: x = 10 Strict mode error: y is not defined
Duplicate Parameter Names
// Non-strict mode allows duplicates
function nonStrictDuplicate(a, a) {
console.log("Non-strict duplicate param:", a);
}
// Strict mode prevents duplicates (would throw SyntaxError)
console.log("Strict mode prevents duplicate parameter names");
nonStrictDuplicate(1, 2); // Uses last value
Strict mode prevents duplicate parameter names Non-strict duplicate param: 2
Comparison Table
| Feature | Non-Strict Mode | Strict Mode |
|---|---|---|
| Undeclared variables | Creates global variable | Throws ReferenceError |
| Duplicate parameters | Allowed | SyntaxError |
| Deleting variables | Ignored silently | Throws error |
| this in functions | Global object | undefined |
Function-Level Strict Mode
function mixedExample() {
// Non-strict function
implicitGlobal = "created";
function innerStrict() {
"use strict";
try {
anotherGlobal = "error";
} catch (error) {
console.log("Inner function error:", error.message);
}
}
innerStrict();
console.log("Outer function created:", implicitGlobal);
}
mixedExample();
Inner function error: anotherGlobal is not defined Outer function created: created
Conclusion
Strict mode catches common coding mistakes and prevents unsafe actions. It's recommended for all new JavaScript projects to avoid subtle bugs and improve code quality.
Advertisements
