Spex3
    

JavaScript Comparison Operators 🔍


    

    

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

1️⃣ List of Comparison Operators
Operator Symbol Example Result
Equal to == 5 == "5" true (loose equality)
Strict equal to === 5 === "5" false (strict equality)
Not equal to != 5 != "5" false (loose inequality)
Strict not equal to !== 5 !== "5" true (strict inequality)
Greater than > 10 > 5 true
Less than < 10 < 5 false
Greater than or equal to >= 10 >= 10 true
Less than or equal to <= 10 <= 5 false

2️⃣ Explanation and Examples
✅ 1. Equal to (==)
Checks if two values are equal in value, but ignores data types (performs type coercion).


console.log(5 == "5"); // true (string "5" is converted to number 5)
console.log(0 == false); // true (false is converted to 0)
console.log(null == undefined); // true (special case)

📌 Caution: Avoid == due to unexpected type coercion.

✅ 2. Strict Equal to (===)
Checks if two values are equal in value and type (no type conversion).


console.log(5 === "5"); // false (number ≠ string)
console.log(0 === false); // false (boolean ≠ number)
console.log(null === undefined); // false

📌 Best Practice: Use === to prevent unexpected results.

✅ 3. Not Equal to (!=)
Checks if two values are not equal in value, but ignores types (loose inequality).


console.log(5 != "5"); // false (type coercion makes them equal)
console.log(10 != "10"); // false
console.log(0 != false); // false

📌 Caution: Avoid != because of unexpected type coercion.

✅ 4. Strict Not Equal to (!==)
Checks if two values are not equal in value or type.


console.log(5 !== "5"); // true (number ≠ string)
console.log(10 !== 10); // false (both are numbers)
console.log(0 !== false); // true (boolean ≠ number)

📌 Best Practice: Use !== to avoid unintended type coercion.

✅ 5. Greater Than (>) and Less Than (<)

console.log(10 > 5); // true
console.log(10 < 5); // false
console.log("b" > "a"); // true (compares Unicode values)
console.log("2" > 1); // true (string "2" is converted to number 2)

📌 Note: Strings are compared based on Unicode values.

✅ 6. Greater Than or Equal (>=) and Less Than or Equal (<=)

console.log(10 >= 10); // true
console.log(5 <= 10); // true
console.log("apple" >= "banana"); // false (Unicode comparison)

3️⃣ Best Practices
✅ Use === and !== instead of == and != to avoid type coercion.
✅ Be careful with string comparisons (they use Unicode order).
✅ Avoid comparing null and undefined directly (null == undefined is true).


    Date: 2025-03-29 00:00:00.000000