JS Strict Mode
In this page:
"use strict";
// strict mode code
What Is Strict Mode?
Strict mode makes JavaScript more careful. It catches some common mistakes. Enable it by adding 'use strict'; at the top of a file or function, which changes several silent failures into thrown errors instead.
उदाहरण: What Is Strict Mode?
"use strict";
console.log("Strict mode is on for this script.");
Prevent Accidental Globals
Strict mode prevents assigning a value to an undeclared variable. Without strict mode, x = 5 on an undeclared variable quietly creates a global variable — strict mode throws a ReferenceError instead, catching the typo immediately.
उदाहरण: Prevent Accidental Globals
"use strict";
try {
x = 5; // undeclared variable
} catch (e) {
console.log(e.message); // ReferenceError
}
Strict Function Calls
In a strict regular function call, this is undefined instead of the global object. This difference matters for code relying on this to detect whether a function was called as a standalone function versus as an object method.
उदाहरण: Strict Function Calls
"use strict";
function show() {
console.log(this); // undefined, not global object
}
show();
Strict Function Parameters
Strict mode rejects duplicate parameter names. Use clear and unique parameter names.
Without strict mode, function f(a, a) {} silently allows the duplicate and the second a shadows the first — strict mode throws a SyntaxError instead, surfacing the mistake early.
उदाहरण: Strict Function Parameters
"use strict";
try {
eval("function f(a, a) {}"); // duplicate parameter names
} catch (e) {
console.log(e.constructor.name); // SyntaxError
}
Best Practice
Use strict mode in older script-based code when you want stronger error checking. Modern JavaScript modules are strict by default.
Since ES module code and class bodies are automatically strict, most modern JavaScript benefits from these protections without an explicit directive.
उदाहरण: Best Practice
class Example {
// class bodies are strict by default, no directive needed
show() { console.log(this); }
}
new Example().show();
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: