JS शॉर्ट सर्किट इवैल्यूएशन
In this page:
const result = a || b; // first truthy value
const result = a && b; // b if a is truthy
condition && doSomething();
AND Short Circuit
&& बाएं से दाएं evaluate होता है और किसी falsy value पर पहुंचते ही रुक जाता है, क्योंकि overall result पहले ही तय हो चुका है। उस स्थिति में दाईं तरफ का expression कभी evaluate नहीं होता।
उदाहरण: AND Short Circuit
console.log(false && console.log("never runs"));
OR Short Circuit
|| किसी truthy value पर पहुंचते ही रुक जाता है, क्योंकि सिर्फ वही value result तय कर देती है। इस 'short circuit' व्यवहार का मतलब है कि दूसरा operand हमेशा execute नहीं होता।
उदाहरण: OR Short Circuit
console.log(true || console.log("never runs"));
Short Circuit Function Calls
चूंकि result पता चलते ही JavaScript दाईं तरफ को evaluate करना छोड़ देता है, आप किसी function को conditionally कॉल करने के लिए && इस्तेमाल कर सकते हैं: isReady && doSomething() सिर्फ तभी doSomething को कॉल करता है जब isReady truthy हो।
उदाहरण: Short Circuit Function Calls
const isReady = true;
isReady && console.log("Doing something");
Default Values
|| आमतौर पर एक fallback देने के लिए इस्तेमाल होता है: const name = input || Guest input के truthy होने पर उसे इस्तेमाल करता है, वरना Guest पर fallback होता है — हालांकि numeric/boolean defaults के लिए अक्सर ?? ज़्यादा सुरक्षित होता है।
उदाहरण: Default Values
// Declare the constant `input`, set to ""
// Declare the constant `input`, set to ""
const input = "";
// Declare the constant `name`, set to `input || "Guest"`
// Declare the constant `name`, set to `input || "Guest"`
const name = input || "Guest";
// Print `name` to the console
// Print `name` to the console
console.log(name);
Short Circuit Evaluation के नियम
यही short-circuit नियम है जो आपको कई && या || conditions को कुशलता से chain करने देता है: evaluation उसी पल रुक जाता है जब आखिरी outcome पहले ही तय हो चुका होता है, अनावश्यक काम को skip करते हुए।
उदाहरण: Short Circuit Evaluation Rules
const a = false, b = true, c = true;
console.log(a && b && c); // stops at a
console.log(a || b || c); // stops at b
- defaults के लिए
&&इस्तेमाल करना, जबकिa && bfalsy होने परareturn करता है,bनहीं। 0या empty string valid होने पर defaults के लिए||इस्तेमाल करना, जो गलती से उन्हें replace कर देता है।ok && doWork()जैसे side effects के लिए short-circuiting पर निर्भर रहना, जो एकifके मुकाबले पढ़ने में मुश्किल है।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: