? JavaScript Strict Mode
⚡ Quick Overview
Strict mode is a safer and more controlled version of JavaScript introduced in ECMAScript 5. It helps developers avoid silent errors, prevents accidental global variables, and disallows risky language features that can introduce bugs.
It is enabled by placing the directive "use strict"; at the top of a script or inside a function.
? Key Concepts
- Strict mode is optional and must be explicitly enabled.
- It can be applied globally or only inside a function.
- Using undeclared variables causes an error instead of creating globals.
- Invalid operations throw errors rather than failing silently.
- Some words become reserved and cannot be used as identifiers.
this inside a normal function becomes undefined.
? Syntax and Theory
Strict mode works using a directive: a plain string expression at the beginning of code.
- It must appear as the first statement.
- Accepted formats are
"use strict"; and 'use strict';.
- If placed incorrectly, it behaves like a normal string.
? Code Examples
? Global strict mode with undeclared variable
? Function-level strict mode
function example() {
"use strict";
y = 20;
}
? this in strict mode
"use strict";
function test() {
console.log(this);
}
test();
? Live Output and Explanation
? What Happens?
- Strict mode prevents accidental creation of global variables.
- Function-only strict mode limits behavior only inside that block.
this inside a normal function becomes undefined.
- Errors become visible early instead of causing silent bugs.
? When to Use Strict Mode
- While learning JavaScript for better error feedback.
- In production code to prevent hidden bugs.
- In large projects to reduce unpredictable behavior.
? Tips and Best Practices
- Always place
"use strict"; at the top.
- Declare variables using
let, const, or var.
- Use strict mode in new projects by default.
- Do not rely on outdated JavaScript behavior.
? Try It Yourself
- Enable strict mode and test undeclared variables.
- Try using a reserved keyword as a variable name.
- Compare
this in strict and non-strict functions.
- Attempt to delete variables and observe errors.