Strict Mode in JavaScript is a way to opt in to a restricted version of JavaScript, helping you write more secure, error-free code.
🔹 How to Enable Strict Mode:
Place "use strict"; at the beginning of a script or a function:
"use strict";
function test() {
// code runs in strict mode
}
✅ Key Features of Strict Mode:
- Prevents usage of undeclared variables.
- Makes assignments to read-only properties throw errors.
- Disallows duplicate parameter names in functions.
- Disables
withstatement. - Throws error on assigning to non-writable global variables like
NaN. - Makes
thisinside functions default toundefinedinstead of the global object.
❌ Without Strict Mode:
x = 10; // No error, implicitly creates global variable
✅ With Strict Mode:
"use strict";
x = 10; // ❌ ReferenceError: x is not defined
📝 In Summary:
Strict mode makes JavaScript code more robust by catching common mistakes early and preventing unsafe actions—it's a best practice to use it, especially in large or team-based projects.