JavaScript Comparison Operators

JavaScript Comparison Operators

JavaScript Comparison Operators 🔍

Comparison operators in JavaScript compare two values and return a Boolean (true or false).

1️⃣ Types of Comparison Operators

OperatorNameExampleReturns
==Equal to5 == "5"true (loose equality)
===Strict equal to5 === "5"false (strict equality)
!=Not equal to5 != "5"false
!==Strict not equal to5 !== "5"true
>Greater than10 > 5true
<Less than3 < 5true
>=Greater than or equal to5 >= 5true
<=Less than or equal to4 <= 5true

2️⃣ Loose vs. Strict Equality (== vs. ===)

🔹 == (Loose Equality): Converts data types before comparing.
🔹 === (Strict Equality): Does not convert types, checks both value & type.

console.log(5 == "5"); // true (type conversion happens) console.log(5 === "5"); // false (different types: number & string)

Always use === for accurate comparisons!

3️⃣ Not Equal (!= vs. !==)

  • != (loose inequality) converts types before comparison.
  • !== (strict inequality) does not convert types.
console.log(5 != "5"); // false (values are the same after conversion) console.log(5 !== "5"); // true (different types)

Use !== for accurate comparisons!

4️⃣ Comparing Numbers

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

5️⃣ Comparing Strings

🔹 JavaScript compares strings based on Unicode order (character-by-character).
🔹 Uppercase letters come before lowercase letters.

console.log("apple" > "banana"); // false ("a" comes before "b") console.log("cat" > "bat"); // true ("c" comes after "b") console.log("Zoo" > "apple"); // true (Uppercase "Z" comes before lowercase "a")

6️⃣ Comparing Different Data Types

  • JavaScript converts non-numbers to numbers when comparing.
console.log("10" > 5); // true ("10" becomes 10) console.log("2" > "12"); // true ("2" is greater than "1" in "12") console.log(true == 1); // true (true becomes 1) console.log(false == 0); // true (false becomes 0) console.log(null == 0); // false (special case) console.log(null >= 0); // true (null becomes 0) console.log(undefined == 0); // false (undefined is never equal to anything except itself)

🚨 Avoid comparisons with null and undefined as they can behave unexpectedly!

🎯 Summary

Use === and !== instead of == and !=
Be cautious when comparing different data types
String comparisons use Unicode order

🚀 Now you're ready to compare values in JavaScript like a pro! Let me know if you need more details. 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close