In JavaScript, "Same-Value-Zero" (or SameValueZero
) is merely a comparison algorithm (used for comparison of 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 |
[] |
[] |
false |
false |
[1, 2] |
[1, 2] |
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 |
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.