JavaScript comparison operators allow you to compare values. Whether you’re checking if two numbers are equal or if your coffee is stronger than your will to work, JavaScript has got your back!
1. Basic Comparison Operators
a) Equality (==
and ===
)
==
(Loose Equality)
Checks if two values are equal, but doesn’t care about type (because JavaScript is too chill).
console.log(5 == "5"); // true (JavaScript is like, "Eh, close enough!")
console.log(0 == false); // true (Wait, what?!)
console.log(null == undefined); // true (They're both kinda nothing?)
===
(Strict Equality)
Checks if values AND types are the same (JavaScript suddenly becomes picky!).
console.log(5 === "5"); // false (No more free passes!)
console.log(0 === false); // false (Strict mode: ON)
console.log(null === undefined); // false (Now they're different!)
b) Inequality (!=
and !==
)
!=
(Loose Inequality)
console.log(5 != "5"); // false (JavaScript is still in "close enough" mode)
console.log(0 != false); // false (Why, JavaScript, why?!)
!==
(Strict Inequality)
console.log(5 !== "5"); // true (Strict mode saves the day!)
console.log(0 !== false); // true (Now JavaScript actually makes sense!)
2. Relational Operators
a) Greater Than (>
)
Checks if the first value is bigger than the second (like comparing your salary to your bills!).
console.log(10 > 5); // true (Math works!)
console.log("apple" > "banana"); // false (Alphabet wars)
b) Less Than (<
)
Opposite of >
(For those who like things in reverse!)
console.log(2 < 10); // true (Duh!)
console.log("cat" < "dog"); // true (Alphabet again!)
c) Greater Than or Equal (>=
)
console.log(10 >= 10); // true (No arguments here!)
console.log(99 >= 100); // false (Nice try!)
d) Less Than or Equal (<=
)
console.log(5 <= 5); // true (Fair enough)
console.log(1 <= -5); // false (Math strikes again!)
3. The Weird Stuff
NaN Comparisons
NaN
(Not-a-Number) is the rebellious one in JavaScript—it refuses to be equal to anything, even itself!
console.log(NaN == NaN); // false (WHAT?!)
console.log(NaN === NaN); // false (Still nope!)
console.log(isNaN(NaN)); // true (Finally, something that makes sense!)
Fun Facts!
console.log("5" > 4); // true (Wait... what?!)
console.log("5" < 4); // false (Of course...)
console.log("apple" > 5); // false (Apples and numbers don’t mix)
console.log([] == 0); // true (Okay, JavaScript, calm down!)
console.log([] === 0); // false (Strict mode to the rescue!)
Conclusion
Comparison operators in JavaScript are powerful but sometimes ridiculous. Always use ===
to avoid JavaScript’s "creative" type conversions. And if something weird happens... just blame JavaScript!
0 Comments