Lesson 18: Mastering JavaScript Comparisons with challenges!

π§ Internal Mechanics
1. Returns Boolean
All comparisons return true
or false
.
2. String Comparison
Lexicographical order (like dictionary).
Case-sensitive.
Based on Unicode values.
'Z' > 'A' // true
'apple' > 'pineapple' // false ('a' < 'p')
'2' > '12' // true (because '2' > '1' in Unicode)
3. Different Types β Coercion (except with ===
)
'2' > 1 // true β '2' gets converted to number 2
false == 0 // true β both converted to 0
true == 1 // true β both converted to 1
4. Strict Equality ===
No coercion.
Compares both value and type.
0 === false // false
'5' === 5 // false
β οΈ Hidden Quirks and Gotchas
β‘ null
and undefined
Expression | Result | Reason |
null == undefined | true | Special case in spec |
null === undefined | false | Different types |
null > 0 | false | null β 0, but not greater |
null == 0 | false | null β number |
null >= 0 | true | null β 0, so 0 β₯ 0 |
undefined > 0 | false | undefined β NaN |
undefined == 0 | false | undefined only equals null loosely |
π Strict equality is safer.
π§ͺ Real-world Usage
Form field values are usually strings. Comparing them to numbers can lead to tricky bugs.
Defaulting behavior often checks
== null
to cover bothnull
andundefined
.Use
===
in most situations to avoid surprises.In conditionals, prefer truthiness/falsiness with care:
if (value != null) {
// value is not null or undefined
}
π§© Debugging Scenarios
"2" > "12"
returnstrue
β Because it's string comparison:'2'
>'1'
lexicographically.null >= 0
istrue
, butnull > 0
isfalse
β Comparison uses numeric coercion but in subtly different ways.undefined == 0
isfalse
, butfalse == 0
istrue
βfalse β 0
, butundefined
only equalsnull
in loose equality.
πΌ Interview Prep Notes
β Do:
Use
===
and!==
by default.Check
value == null
to test for bothnull
andundefined
.
β Donβt:
Use
==
unless you really know what it does.Compare potentially
null/undefined
values with<
,>
,<=
,>=
without safe-guards.
π§ Mnemonics
"== is loose, === is truth"
β use===
for strict, bug-free checks."Falsy values can trick you!" β always test explicitly.
π― Tasks Recap (with Explanations)
5 > 4 // true β obvious
"apple" > "pineapple" // false β 'a' < 'p'
"2" > "12" // true β '2' > '1' (string comparison)
undefined == null // true β only values that are loosely equal to each other
undefined === null // false β different types
null == "\n0\n" // false β "\n0\n" becomes 0, null β 0
null === +"\n0\n" // false β "\n0\n" β 0 β type mismatch with null
π§ Bonus Mind Map
Comparisons in JS
|
-----------------------------------------
| | |
Strict Loose Type Coercion
(===, !==) (==, !=) -> Number for most ops
| |
Type + Value Only Value β οΈ Tricky with null/undefined
Match Needed Tries to Convert
Subscribe to my newsletter
Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
