JavaScript ยท Chapter 28 of 55

JavaScript Comparison Operators

Comparison operators compare two values and return a boolean. `==` and `!=` perform type coercion before comparing, while `===` and `!==` (strict equality) compare both value and type without coercion.

Best practice is to always use `===` and `!==` to avoid confusing bugs caused by implicit type conversion.

Loose vs strict equality

`5 == '5'` is true because == coerces types before comparing, but `5 === '5'` is false since the types differ (number vs string).

Relational operators

`<`, `>`, `<=`, `>=` compare numbers or strings (lexicographically) and return booleans.

Example 1 (javascript)
console.log(5 == "5");
console.log(5 === "5");
Output
true
false

== coerces types; === requires matching type and value.

Example 2 (javascript)
console.log(10 > 5);
console.log("apple" < "banana");
Output
true
true

Strings compare lexicographically, like dictionary order.

Key points

  • `===` and `!==` check both value and type (strict).
  • `==` and `!=` coerce types before comparing (loose).
  • Always prefer strict equality to avoid surprising bugs.
  • Strings compare lexicographically using Unicode code points.
๐Ÿ’ก Note: '==' comparing null and undefined returns true, but === returns false โ€” one more reason to prefer strict equality.

๐Ÿ“ Quick Quiz

1. What does `5 === '5'` return?

2. Which is the recommended equality operator?

3. What does `'a' < 'b'` return?