🟡 Control Flow  ·  Lesson 16

Comparison and Logic

Comparison और Logic

=== vs == — the most important rule

console.log(5 === 5);      // true   same value, same type
console.log(5 === "5");    // false  ← number vs string: NOT equal
console.log(5 == "5");     // true   ← == converts first! confusing

console.log(0 == false);   // true   ← == says these are equal?!
console.log(0 === false);  // false  ← === correctly says no

console.log(null == undefined);   // true
console.log(null === undefined);  // false
=== (strict equality) compares value AND type. == (loose equality) converts types first, then compares — and that conversion produces bizarre results. Look at 0 == false being true, or "" == 0 being true. These "coercion" rules are complicated, unintuitive, and a rich source of bugs. Professional JavaScript has one universal rule: always use === and !==, never == or !=. If you need to compare different types, convert explicitly with Number() first. This single habit prevents a whole category of mysterious bugs, and it's the most reliable answer you can give in an interview.

Other Comparison Operators

console.log(7 > 3);         // true
console.log(7 >= 7);        // true
console.log(2 < 5);         // true
console.log(5 <= 4);        // false

// Strings compare alphabetically (by character codes):
console.log("apple" < "banana");   // true
console.log("Zebra" < "apple");    // true  ← capitals come first!
The relational operators >, <, >=, <= behave exactly as in maths for numbers. They also work on strings, comparing them character by character using their underlying character codes — which is roughly alphabetical, with one gotcha: ALL capital letters come before ALL lowercase ones, so "Zebra" < "apple" is true. When sorting user-facing text, lowercase everything first (a.toLowerCase() < b.toLowerCase()) to get the expected order.

Logical Operators Recap

let age = 20, hasID = true, isMember = false;

age >= 18 && hasID;             // true   — AND: both must be true
isMember || age >= 60;          // false  — OR: at least one true
!isMember;                      // true   — NOT: flips the boolean

// Combining them (use parentheses for clarity):
(age >= 18 && hasID) || isMember;   // true
Logical operators let you build complex conditions from simple ones. Remember the mental shortcut: && (AND) is demanding — every part must be true. || (OR) is generous — one true part is enough. ! (NOT) simply inverts. When you mix && and || in one expression, && is evaluated before || (like multiplication before addition in maths) — but rather than memorising precedence, use parentheses to make your intent obvious to anyone reading the code, including your future self.

Short-Circuit Evaluation — a clever shortcut

// && stops as soon as it finds a FALSE
false && expensiveCheck();     // expensiveCheck() never runs!

// || stops as soon as it finds a TRUE
true || expensiveCheck();      // expensiveCheck() never runs!

// Practical uses:
let name = userName || "Guest";        // fallback if userName is falsy
isLoggedIn && showDashboard();         // run only if logged in
JavaScript stops evaluating a logical expression as soon as the answer is certain — this is "short-circuiting." With &&, if the left side is false, the whole thing must be false, so the right side is never even run. With ||, if the left is true, the answer is already true. This isn't just an optimisation — it's used deliberately. userName || "Guest" gives a default value when userName is falsy (remember your falsy list!). And isLoggedIn && showDashboard() runs a function only when a condition holds. Both patterns appear constantly in real code.

Common Pitfalls

// 1. Using = instead of ===
if (x = 5) { }      // ✗ ASSIGNS 5 to x (and is always truthy!)
if (x === 5) { }    // ✓ compares

// 2. NaN is not equal to anything, including itself
NaN === NaN;        // false!
Number.isNaN(NaN);  // true  ← use this to test for NaN

// 3. Comparing objects/arrays compares REFERENCES, not contents
[1,2] === [1,2];    // false! (two different arrays in memory)
Three traps worth knowing. First, writing = (assignment) instead of === inside an if silently assigns a value and usually evaluates as truthy — a nasty, hard-to-spot bug. Second, NaN is famously not equal to itself, so NaN === NaN is false; use Number.isNaN() to check for it. Third, comparing two arrays or objects with === checks whether they're the SAME object in memory, not whether their contents match — so two identical-looking arrays are never ===. Keep these three in mind and you'll debug comparison problems much faster.

Exam Corner

Q: Difference between === and == ? === compares value and type; == converts types first. Always use ===.

Q: What is 5 == "5" and 5 === "5"? true and false respectively.

Q: What is short-circuit evaluation? JavaScript stops evaluating once the result is certain (&& on false, || on true).

Q: What does userName || "Guest" do? Uses userName if truthy, otherwise falls back to "Guest".

Q: Is NaN === NaN true? No — it's false. Use Number.isNaN() to test for NaN.

=== vs == — सबसे ज़रूरी rule

console.log(5 === 5);      // true   same value, same type
console.log(5 === "5");    // false  ← number vs string: barabar NAHI
console.log(5 == "5");     // true   ← == pehle badalta hai! uljhan

console.log(0 == false);   // true   ← == kehta ye barabar hain?!
console.log(0 === false);  // false  ← === sahi kehta nahi

console.log(null == undefined);   // true
console.log(null === undefined);  // false
=== (strict equality) value AUR type तुलना करता है. == (loose equality) पहले types बदलता है, फिर तुलना — और वह conversion अजीब नतीजे देता है. देखिए 0 == false true है, या "" == 0 true. ये "coercion" rules जटिल, अस्वाभाविक, और bugs का समृद्ध स्रोत हैं. Professional JavaScript का एक universal rule है: हमेशा === और !== use कीजिए, कभी == या != नहीं. अगर अलग types तुलना करनी हो, पहले Number() से साफ-साफ बदलिए. यह एक आदत bugs की पूरी श्रेणी रोकती है, और interview में आप जो सबसे भरोसेमंद जवाब दे सकते हैं.

अन्य Comparison Operators

console.log(7 > 3);         // true
console.log(7 >= 7);        // true
console.log(2 < 5);         // true
console.log(5 <= 4);        // false

// Strings varnkram me tulna karti hain (character codes se):
console.log("apple" < "banana");   // true
console.log("Zebra" < "apple");    // true  ← capitals pehle aate hain!
Relational operators >, <, >=, <= numbers के लिए ठीक गणित जैसा व्यवहार करते हैं. वे strings पर भी चलते हैं, उन्हें अपने अंतर्निहित character codes से character-दर-character तुलना करते — जो मोटे तौर पर वर्णक्रम है, एक gotcha के साथ: SAARE capital letters SAARE lowercase से पहले आते हैं, तो "Zebra" < "apple" true है. User को दिखने वाला text sort करते समय, अपेक्षित order पाने को पहले सब lowercase कीजिए (a.toLowerCase() < b.toLowerCase()).

Logical Operators दोहराव

let age = 20, hasID = true, isMember = false;

age >= 18 && hasID;             // true   — AND: dono true hone chahiye
isMember || age >= 60;          // false  — OR: kam se kam ek true
!isMember;                      // true   — NOT: boolean palatta

// Inhe milana (saafi ke liye parentheses use karo):
(age >= 18 && hasID) || isMember;   // true
Logical operators आपको सरल से जटिल conditions बनाने देते हैं. मानसिक shortcut याद रखिए: && (AND) मांग करने वाला है — हर हिस्सा true होना चाहिए. || (OR) उदार है — एक true हिस्सा काफी है. ! (NOT) बस उलटता है. जब आप एक expression में && और || मिलाएं, && || से पहले evaluate होता है (गणित में जोड़ से पहले गुणा जैसा) — पर precedence याद करने के बजाय, parentheses use कीजिए ताकि आपका इरादा code पढ़ने वाले किसी को भी साफ हो, आपके भविष्य के खुद को भी.

Short-Circuit Evaluation — चतुर shortcut

// && FALSE milte hi ruk jata hai
false && expensiveCheck();     // expensiveCheck() kabhi nahi chalta!

// || TRUE milte hi ruk jata hai
true || expensiveCheck();      // expensiveCheck() kabhi nahi chalta!

// Vyavharik upyog:
let name = userName || "Guest";        // agar userName falsy to fallback
isLoggedIn && showDashboard();         // sirf logged in hone par chalao
JavaScript logical expression evaluate करना रोक देता है जैसे ही जवाब निश्चित हो — यह "short-circuiting" है. && के साथ, अगर बायां पक्ष false है, पूरी चीज़ false ही होगी, तो दायां पक्ष कभी चलता ही नहीं. || के साथ, अगर बायां true है, जवाब पहले से true है. यह सिर्फ optimisation नहीं — यह जानबूझकर use होता है. userName || "Guest" userName falsy होने पर default value देता है (अपनी falsy list याद है!). और isLoggedIn && showDashboard() function सिर्फ तब चलाता है जब condition पूरी हो. दोनों patterns असली code में लगातार आते हैं.

आम गलतियां

// 1. === ke bajaye = use karna
if (x = 5) { }      // ✗ x me 5 ASSIGN karta (aur hamesha truthy!)
if (x === 5) { }    // ✓ tulna karta

// 2. NaN kisi ke barabar nahi, khud ke bhi nahi
NaN === NaN;        // false!
Number.isNaN(NaN);  // true  ← NaN test karne ko yeh use karo

// 3. Objects/arrays ki tulna REFERENCES ki hoti hai, contents ki nahi
[1,2] === [1,2];    // false! (memory me do alag arrays)
तीन जाल जानने लायक. पहला, if के अंदर === के बजाय = (assignment) लिखना चुपचाप value assign करता है और आमतौर पर truthy evaluate होता है — गंदा, पकड़ने में मुश्किल bug. दूसरा, NaN मशहूर रूप से खुद के बराबर नहीं, तो NaN === NaN false है; इसे जांचने को Number.isNaN() use कीजिए. तीसरा, दो arrays या objects की === से तुलना जांचती है क्या वे memory में VAHI object हैं, उनके contents match करते हैं या नहीं यह नहीं — तो दो एक जैसी दिखने वाली arrays कभी === नहीं होतीं. इन तीन को ध्यान में रखिए और comparison problems कहीं तेज़ी से debug करेंगे.

Exam Corner

Q: === और == में अंतर? === value और type तुलना करता; == पहले types बदलता. हमेशा === use कीजिए.

Q: 5 == "5" और 5 === "5" क्या हैं? क्रमशः true और false.

Q: Short-circuit evaluation क्या है? नतीजा निश्चित होते ही JavaScript evaluate करना रोक देता है (&& false पर, || true पर).

Q: userName || "Guest" क्या करता है? userName truthy हो तो उसे use करता, वरना "Guest" पर fallback.

Q: क्या NaN === NaN true है? नहीं — यह false है. NaN test करने को Number.isNaN() use कीजिए.
← Back to JavaScript Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

इस पेज का code यहाँ तैयार है — बदलिए और तुरंत नतीजा देखिए. कुछ install किए बिना.
👁 Live Preview
सब कुछ आपके browser में ही चलता है — कोई server, कोई signup नहीं. JavaScript का console.log देखने के लिए F12 दबाइए.