What Is "Same-Value-Zero" in JavaScript?

JavaScript SameValueZero algorithm explained

In JavaScript, "Same-Value-Zero" (or SameValueZero) is merely a comparison algorithm (used for comparison two values), which is, for example, used by Array.prototype.includes() and TypedArray.prototype.includes(), as well as, Map and Set methods for comparing key equality.

The Same-Value-Zero algorithm is similar to doing the strict equality (===) value comparison. However, they differ in terms of how they perform NaN equality — i.e. strict equality treats NaN as unequal to itself, whereas Same-Value-Zero does not:

x y === SameValueZero
NaN NaN false true

For example:

// ES7+
console.log([NaN].includes(NaN)); // true

console.log(NaN === NaN); // false

Other than this one difference, both (Same-Value-Zero algorithm and strict equality) yield the same result:

x y === SameValueZero
undefined undefined true true
null null true true
true true true true
false false true true
'foo' 'foo' true true
0 0 true true
+0 -0 true true
+0 0 true true
-0 0 true true
0n -0n true true
0 false false false
"" false false false
"" 0 false false
'0' 0 false false
'23' 23 false false
[1, 2] '1,2' false false
new String('foo') 'foo' false false
null undefined false false
null false false false
undefined false false false
{ foo: 'bar' } { foo: 'bar' } false false
new String('foo') new String('foo') false false
0 null false false
0 NaN false false
'foo' NaN false false

Hope you found this post useful. It was published . Please show your love and support by sharing this post.