JavaScript Equality Explained: How to Master Comparisons and Sameness

5/5 - (1 vote)

Introduction:

When programming in JavaScript, comparing values is a common task. But did you know that there are different ways to check if values are equal? JavaScript offers multiple tools for equality comparison, each with its unique behavior. In this post, we’ll explore JavaScript’s value comparison operators (==, ===, Object.is()) and dive deep into equality algorithms like isLooselyEqual, isStrictlyEqual, SameValueZero, and SameValue. By the end of this guide, you’ll understand how and when to use these different methods to ensure your code behaves exactly as you expect.

Hook: Ever wondered why 5 == "5" returns true but 5 === "5" returns false? Let’s find out!

1. Understanding Equality in JavaScript

In JavaScript, equality comparisons are a way to check if two values are considered the same. However, JavaScript has several ways to compare values, and not all comparisons behave in the same way. For beginners, this can be confusing because what might seem like two equal values could be treated as unequal depending on the type of comparison you use.

This is why it’s important to understand the difference between loose equality (==), strict equality (===), and Object.is().

2. Value Comparison Operators

JavaScript provides two primary operators for comparing values: == (loose equality) and === (strict equality). These operators are used to compare two values to check if they are equal, but they work differently.

Loose Equality (==)

The loose equality operator (==) checks if two values are equal after performing type coercion. Type coercion is when JavaScript automatically converts one or both values to the same type before comparing them.

Example:

console.log(5 == '5'); // true
JavaScript

Here, JavaScript converts the string '5' to the number 5, so the comparison is true.

Strict Equality (===)

The strict equality operator (===) checks if two values are exactly equal without performing type coercion. Both the type and value must be the same for the comparison to return true.

Example:

console.log(5 === '5'); // false
JavaScript

Since one value is a number and the other is a string, the strict equality comparison returns false.

The Object.is() Method

The Object.is() method is another way to compare values in JavaScript, introduced in ECMAScript 2015 (ES6). It checks if two values are the same, but it behaves slightly differently than === in certain cases.

Example:

console.log(Object.is(NaN, NaN)); // true
console.log(NaN === NaN); // false
JavaScript

In the first case, Object.is() correctly identifies that NaN is equal to NaN, while === does not.

Here’s when to use Object.is():

  • It considers NaN equal to NaN, unlike ===.
  • It treats +0 and -0 as different values, while === treats them as equal.

3. Equality Algorithms

JavaScript’s comparison operators rely on built-in algorithms for checking equality. Let’s explore these algorithms in detail.

isLooselyEqual

The isLooselyEqual algorithm is used when you use the == operator. It first attempts to convert the values to the same type and then compares them.

Example:

console.log(1 == '1'); // true
JavaScript

In this case, the algorithm converts the string '1' to the number 1 before comparing them.

isStrictlyEqual

The isStrictlyEqual algorithm is used by the === operator. It checks if the values are of the same type and then compares them without type coercion.

Example:

console.log(1 === '1'); // false
JavaScript

Since the values are of different types, the comparison returns false.

SameValue

The SameValue algorithm is used by Object.is(). It’s similar to ===, but it handles NaN and +0/-0 differently. This algorithm considers NaN to be equal to itself and distinguishes between +0 and -0.

Example:

console.log(Object.is(NaN, NaN)); // true
JavaScript

SameValueZero

The SameValueZero algorithm is used in certain internal JavaScript operations, such as Set or Map. It’s similar to SameValue, but it does not differentiate between +0 and -0.

Example:

let mySet = new Set([0, -0]);
console.log(mySet.size); // 1
JavaScript

4. Comparing the Comparisons

Now that we understand the different comparison methods and algorithms, let’s compare them side by side.

OperatorType CoercionHandles NaNDifferentiates +0 and -0
==YesNoNo
===NoNoNo
Object.is()NoYesYes
SameValueZeroNoYesNo

This table clearly shows the differences between these comparison methods, helping you decide which one to use in different scenarios.

5. Practical Examples and Use Cases

Let’s explore some real-world examples to help you understand when and where to use these operators.

Example 1: Loose vs. Strict Equality in User Input

When comparing user input to a known value, it’s generally safer to use === to avoid unexpected type coercion.

let userInput = '5';
if (userInput === 5) {
  console.log('This will not run');
}
JavaScript

Example 2: Using Object.is() for Special Cases

If you need to check if a value is NaN, use Object.is() instead of ===.

console.log(Object.is(NaN, NaN)); // true
console.log(NaN === NaN); // false
JavaScript

Conclusion

Equality comparisons in JavaScript can be tricky, especially with multiple methods available. By understanding the differences between loose equality (==), strict equality (===), and Object.is(), you can write more accurate and bug-free code. The key is knowing when to use each method based on the context of your comparison.

Keep experimenting with these operators in your code, and soon you’ll feel confident in mastering JavaScript’s equality comparisons!

References:

  1. MDN Web Docs – Equality Comparisons
  2. W3Schools – JavaScript Equality Operators

Spread the love

Leave a Comment