Website logo
Menu

Equality of values in JavaScript

Author's avatar
José Miguel Álvarez VañóDecember 11, 2022

I'm currently doing the JustJavascript course, which I highly recommend, and I've learned how equality of values works in JavaScript.

There are 3 kinds of equality in JavaScript.

Same value equality

Object.is(a, b)  tells us if  a  and  b  are the same value:

Object.is(2, 2); // 🟢 true
Object.is(undefined, undefined); // 🟢 true
Object.is(null, null); // 🟢 true
Object.is(true, true); // 🟢 true
Object.is(1, 1); // 🟢 true
Object.is(-1, -1); // 🟢 true
Object.is("Hello", "Hello"); // 🟢 true
Object.is({}, {}); // 🔴 false
Object.is([], []); // 🔴 false

Strict equality

Strict equality works like Object.is but there are two exceptions.

  1. NaN === NaN  is  false, although they are the same value in JavaScript.

There are some ways to safely check if two values are NaN:

NaN === NaN; // 🔴 false
Object.is(NaN, NaN); // 🟢 true
Number.isNaN(NaN); // 🟢 true
NaN !== NaN; // 🟢 true
  1. -0 === 0  and  0 === -0  are  true, although they are different values in JavaScript.

In the common math that we all learn at school negative zero does not exist, but it exists in floating-point math for practical reasons.

0 === -0; // 🟢 true
Object.is(0, -0); // 🔴 false

Loose equality

Loose equality is very confusing and that's why it's recommended not to use it. As an example, see these cases:

[[]] == ""; // true
true == [1]; // true
false == [0]; // true

If you still want to learn how it works, you can read more about it here.

Resources

GitHub profileTwitter profileLinkedIn profile
José Miguel Álvarez Vañó
© 2023
jmalvarez.dev