[JavaScript] Comprehensive Guide to Comparison Operators and the Pitfalls of Object Comparison

目次

Overview

Comparison operators are used in program control flow, such as if statements, to determine if two values are equal or which value is larger. JavaScript provides two types of equality operators: the “Equality Operator (==)”, which allows type conversion, and the “Strict Equality Operator (===)”, which strictly checks both value and type. This article explains everything from basic numerical and string comparisons to “array (object) comparison,” which is a common stumbling block for beginners.

Specifications (Input/Output)

  • Input: Data such as numbers, strings, or arrays.
  • Output: A boolean value (true or false) as the comparison result.

Basic Usage

A comparison operator compares the left and right sides and returns the result as a boolean type.

List of Comparison Operators

OperatorMeaningDescription
==EqualReturns true if values are equal (allows type conversion).
===Strict EqualReturns true if both value and type are equal (Recommended).
!=Not EqualReturns true if values are not equal (allows type conversion).
!==Strict Not EqualReturns true if the value or type is different (Recommended).
<Less ThanReturns true if the left side is smaller than the right.
>Greater ThanReturns true if the left side is larger than the right.
<=Less Than or EqualReturns true if the left side is equal to or smaller than the right.
>=Greater Than or EqualReturns true if the left side is equal to or larger than the right.

Full Code (HTML / JavaScript)

HTML (index.html)

This is a simple screen to guide the user to the console for result confirmation.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Comparison Operator Demo</title>
    <script src="comparison-demo.js" defer></script>
</head>
<body>
    <div class="container">
        <h1>Check the Console</h1>
        <p>Comparison results (true/false) are displayed in the console.</p>
    </div>
</body>
</html>

JavaScript (comparison-demo.js)

This code demonstrates basic comparisons and the behavior of array comparison (reference comparison).

/**
 * Demo for verifying comparison operator behavior
 */
const runComparisonDemo = () => {
    console.log('--- 1. Basic Value Comparison ---');
    
    // String comparison (equality)
    console.log('"Suzuki" == "Suzuki":', "Suzuki" == "Suzuki"); // true
    
    // Numerical comparison
    console.log('10 < 30:', 10 < 30);   // true
    console.log('20 >= 30:', 20 >= 30); // false


    console.log('--- 2. The Trap of Array (Object) Comparison ---');
    
    // Pattern A: Same content but in "different boxes"
    const array1 = [1, 2, 3];
    const array2 = [1, 2, 3];
    
    // In JavaScript, using == with objects compares the "memory location."
    // Since the content is the same but the locations are different, this returns false.
    console.log('Separate arrays [1,2,3] == [1,2,3]:', array1 == array2); // false


    // Pattern B: Pointing to the "same box" (Pass-by-reference)
    const array3 = [1, 2, 3];
    const array4 = array3; // Copying the location information of array3
    
    // Since they point to the same location, this returns true.
    console.log('Reference-copied array == Original array:', array3 == array4); // true


    console.log('--- 3. Importance of the Strict Equality Operator (===) ---');
    
    const num = 100;
    const str = "100";
    
    // == converts types automatically before comparison (can lead to bugs).
    console.log('100 == "100":', num == str);  // true
    
    // === returns false if the types are different (Safar).
    console.log('100 === "100":', num === str); // false
};

// Execute
runComparisonDemo();

Customization Points

  • Choosing between == and ===: Unless there is a specific reason, use === (strict equality). == can cause bugs because of counter-intuitive behaviors, such as "1" == 1 returning true.
  • Inequality Operators: Similarly, use !== instead of != when checking if values are not equal.

Important Points

  • Object Comparison (Reference Comparison): For arrays and objects, === returns false if the memory addresses are different, even if the internal data is identical. To check if the content is the same, use the method described in the “Advanced Usage” section.
  • Floating Point Comparison: The expression $0.1 + 0.2 === 0.3$ returns false due to floating-point errors. Numerical equality for decimals should be determined by checking if the difference falls within an acceptable range (epsilon).

Advanced Usage

Comparing the Contents of Arrays or Objects

The simplest way to compare the internal data is to stringify (convert to JSON) the contents.

const listA = [1, 2, 3];
const listB = [1, 2, 3];

// Compare after converting to strings
const isSameContent = JSON.stringify(listA) === JSON.stringify(listB);
console.log(isSameContent); // true

Summary

Standard comparisons should utilize === and !== while avoiding == to prevent unexpected type conversion. It is critical to remember that using === with arrays or objects checks if they share the same memory location rather than checking if their internal data is identical. Numerical comparisons for magnitude, such as < and >=, function as expected.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次