DEV Community

José Miguel Álvarez Vañó
José Miguel Álvarez Vañó

Posted on • Originally published at jmalvarez.dev

Equality of values in JavaScript

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).
  • Strict equality: a === b (triple equals).
  • Loose equality: a == b (double equals).

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
Enter fullscreen mode Exit fullscreen mode

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:

  • Number.isNaN(variable)
  • Object.is(variable, NaN)
  • variable !== variable
NaN === NaN; // 🔴 false
Object.is(NaN, NaN); // 🟢 true
Number.isNaN(NaN); // 🟢 true
NaN !== NaN; // 🟢 true
Enter fullscreen mode Exit fullscreen mode

2. -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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Resources

Top comments (0)