== vs. === in JavaScript

You got it! Let’s dive a bit deeper into the differences between == and === in JavaScript and why understanding them is essential:

== (Loose Equality or Abstract Equality): 🧠 Main idea:

== compares values after performing type coercion, meaning it converts the values to the same type before comparing.

Example 1: Comparing different types

javascript
1console.log(5 == '5'); // true

JavaScript coerces the string '5' to a number before comparing, so it results in true.

Example 2: Comparing null and undefined

javascript
1console.log(null == undefined); // true

null and undefined are considered equal when using ==, even though they are different types.

=== (Strict Equality): 🧠 Main idea:

=== compares both the value and the type without performing any type coercion.

Example 1: Comparing different types

javascript
1console.log(5 === '5'); // false

No coercion happens here, so the number 5 and the string '5' are not the same.

Example 2: Comparing null and undefined

javascript
1console.log(null === undefined); // false

null and undefined are not equal with === because their types are different (null is an object, undefined is undefined).

Key Differences:

javascript
1console.log(5 == '5'); // true 2console.log(5 === '5'); // false

Why Use ===?

  • Predictable: === avoids unexpected behavior caused by type coercion.
  • Best practice: Always use === for explicit comparison. It makes your code clearer and safer.
  • Avoiding bugs: When using ==, you might encounter tricky issues (like comparing null and undefined), leading to hard-to-find bugs.