Value-Based Comparison Operators for Arrays of Primitives in JavaScript

Proposal: https://github.com/tc39/proposal-array-value-comparison-operators


Introduction

This proposal introduces value-based comparison behaviors for arrays of primitive values in JavaScript using either enhancements to the == operator or the introduction of new operators (#==, &==, |==).

Currently, JavaScript only supports reference comparison for arrays using both == and ===, which can lead to unintuitive behavior in common use cases where developers expect arrays with the same primitive values to be considered equal.


Problem Statement

JavaScript supports array destructuring, which is clean and expressive:

const [a, b, c] = [1, 2, 3];

But checking that these variables match specific values becomes verbose:

if (a === 1 && b === 2 && c === 3) {
  // do something
}

Trying the intuitive way fails:

if ([a, b, c] == [1, 2, 3]) {
  // false — even though values are the same
}

This is because == compares arrays by reference, not by value.

Why This Is a Problem

This behavior is inconsistent with how == works for primitives:

2 == "2" // true 

But:

[1, 2, 3] == [1, 2, 3] // false 

Proposal Part 1: Improve == or Introduce #== for Array Value Comparison

Option A: Make == Compare Arrays by Value (Only for Primitives)

Allow:

if ([a, b, c] == [1, 2, 3]) {
  // true 
}

Only when:

  • Both sides are arrays of the same length
  • All elements are primitive values (number, string, boolean)

Keep === unchanged (still compares by reference).


Option B: Add a New Operator: #==

If modifying == behavior is not preferred (due to backward compatibility concerns), introduce a new operator:

if ([a, b, c] #== [1, 2, 3]) {
  // true 
}

This operator would only compare arrays by value — ideal for destructured values.


Proposal Part 2: Add Logical Value Comparison Operators: &== and |==

To simplify more complex checks, introduce:

&==: All elements match

Equivalent to:

if (a === 1 && b === 2 && c === 3)

Syntax:

if ([a, b, c] &== [1, 2, 3]) {
  // true only if all match
}

|==: Any element matches

Equivalent to:

if (a === 1 || b === 2 || c === 3)

Syntax:

if ([a, b, c] |== [1, 2, 3]) {
  // true if any match
}

3 Likes

We are extremely unlikely to add new syntax for this, and we definitely can't change the behavior of == without breaking everything.

But we might add a new function for doing element-wise comparison of arrays (there is an old proposal, though it hasn't had movement for a long time). This comes up fairly often; see e.g. this conversation or this thread.

3 Likes