JS स्ट्रिक्ट मोड
In this page:
"use strict";
// strict mode code
Strict Mode क्या है?
Strict mode JavaScript को ज़्यादा सावधान बना देता है। यह कुछ आम गलतियां पकड़ लेता है। किसी file या function के ऊपर 'use strict'; जोड़कर इसे enable करें, जो कई silent failures को thrown errors में बदल देता है।
उदाहरण: What Is Strict Mode?
"use strict";
console.log("Strict mode is on for this script.");
Accidental Globals रोकना
Strict mode किसी undeclared variable को value assign करने से रोकता है। strict mode के बिना, किसी undeclared variable पर x = 5 चुपचाप एक global variable बना देता है — strict mode इसके बजाय एक ReferenceError देता है, typo को तुरंत पकड़ते हुए।
उदाहरण: Prevent Accidental Globals
"use strict";
try {
x = 5; // undeclared variable
} catch (e) {
console.log(e.message); // ReferenceError
}
Strict Function Calls
किसी strict regular function call में, this global object के बजाय undefined होता है। यह फर्क उस code के लिए मायने रखता है जो यह पता लगाने के लिए this पर निर्भर करता है कि किसी function को standalone function के रूप में कॉल किया गया था या object method के रूप में।
उदाहरण: Strict Function Calls
"use strict";
function show() {
console.log(this); // undefined, not global object
}
show();
Strict Function Parameters
Strict mode duplicate parameter names को reject करता है। साफ और unique parameter names इस्तेमाल करें।
strict mode के बिना, function f(a, a) {} चुपचाप duplicate को allow करता है और दूसरा a पहले को shadow कर देता है — strict mode इसके बजाय एक SyntaxError देता है, गलती को जल्दी सामने लाते हुए।
उदाहरण: Strict Function Parameters
"use strict";
try {
eval("function f(a, a) {}"); // duplicate parameter names
} catch (e) {
console.log(e.constructor.name); // SyntaxError
}
Best Practice
जब आपको ज़्यादा मजबूत error checking चाहिए तो पुराने script-based code में strict mode इस्तेमाल करें। Modern JavaScript modules डिफ़ॉल्ट रूप से strict होते हैं।
चूंकि ES module code और class bodies अपने आप strict होते हैं, ज़्यादातर modern JavaScript बिना किसी explicit directive के इन protections का फायदा उठाता है।
उदाहरण: Best Practice
class Example {
// class bodies are strict by default, no directive needed
show() { console.log(this); }
}
new Example().show();
"use strict"को दूसरे statements के बाद जोड़ना, जबकि यह सिर्फ किसी script या function की शुरुआत में काम करता है।- किसी undeclared variable को assign करना, जो strict mode में
ReferenceErrorthrow करता है। - duplicate parameter names या
010जैसे octal literals इस्तेमाल करना, जो strict mode में errors हैं।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: