Day 4:Exploring JavaScript Comparisons: Understanding `==`, `===`, and More

Aman Kumar - Sep 2 - - Dev Community

JavaScript comparisons can sometimes be tricky, especially when dealing with different data types like null and undefined. Today, we’ll explore how comparison operators work and the nuances between == and === in JavaScript.

Basic Comparisons

Let’s start with some basic comparisons:

console.log(2 > 1);   // true
console.log(2 >= 1);  // true
console.log(2 < 1);   // false
console.log(2 == 1);  // false
console.log(2 != 1);  // true
Enter fullscreen mode Exit fullscreen mode

These comparisons are straightforward and work as you would expect. But things get interesting when we introduce null and undefined into the mix.

Comparing null with Numbers

Let’s see what happens when we compare null with numbers:

console.log(null >= 0);  // true
console.log(null === 0); // false
Enter fullscreen mode Exit fullscreen mode

Here’s what’s happening:

  • Comparison Operator (>=): When you use a comparison operator like >=, JavaScript converts null to 0 before making the comparison. So, null >= 0 becomes 0 >= 0, which is true.

  • Strict Equality (===): The strict equality operator does not perform type conversion, so null === 0 is false because null is not the same type as 0.

Comparing undefined with Numbers

Now, let’s look at how undefined behaves:

console.log(undefined >= 0); // false
console.log(undefined == 0); // false
Enter fullscreen mode Exit fullscreen mode
  • Comparison with undefined: Unlike null, undefined does not get converted to 0 during comparison. Instead, the result is always false because undefined is considered "not a number" in this context.

  • Equality Operator (==): Even when using the loose equality operator, undefined does not equal 0. In fact, undefined is only equal to null when using ==.

Understanding == vs ===

  • == (Loose Equality): This operator converts the operands to the same type before making the comparison. This is why null == 0 is false, but null == undefined is true.

  • === (Strict Equality): This operator checks both the value and the type, without any conversion. This is why null === 0 is false, and null === undefined is also false.

Wrapping Up

Understanding how JavaScript handles comparisons is crucial for avoiding unexpected behavior in your code. Whether you’re comparing numbers, dealing with null or undefined, or deciding between == and ===, knowing the details will help you write more predictable and reliable JavaScript.

Happy coding and see you in the next one!!!

. . . . . . . . . . . . . .
Terabox Video Player