In JavaScript spec: http://www.ecma-international.org/publications/standards/Ecma-262.htm
11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
- If Type(x) is different from Type(y), return false.
- If Type(x) is Undefined, return true.
- If Type(x) is Null, return true.
- If Type(x) is Number, then
- If x is NaN, return false.
- If y is NaN, return false.
- If x is the same Number value as y, return true.
- If x is +0 and y is -0, return true.
- If x is -0 and y is +0, return true.
- Return false.
- If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
- If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
- Return true if x and y refer to the same object. Otherwise, return false. NOTE This algorithm differs from the SameValue Algorithm (9.12) in its treatment of signed zeroes and NaNs
What does the bolded section mean? How do you write out some JavaScript to confirm it?
I tried alert(typeof(undefined) === 'x');
but it gives me false
.
Before that it says:
where
x
andy
are value
So first, give x
and y
values.
Then forget "blah", 1 is important. x
and y
have to be the same type to get past step 1.
Step 2 is "If Type(x) is Undefined, return true.".
There is only one value that gives the undefined type, undefined
. Thus, the only way to test step 2 (short of assigning undefined
to variables):
alert(undefined === undefined)
… will give true.
Step 3 works in exactly the same way. The only null value is null
.
alert(null === null)
A manual implementation the algorithm would start like this:
function equalsequalsequals(x, y)
if (typeof x != typeof y) {
return false;
} else if (typeof x == "undefined") {
return true;
} // …
The typeof operator can't tell us if something is null or not, so you can't completely implement the algorithm without using ===
. Since we have ===
, however, we don't need to.
My interpretation is one of reading the spec as a formal proof, having the numbers 2 and 3 dependent on the first rule:
- If Type(x) is different from Type(y), return false.
Since you are at step 2 and have not returned false
, the type of X must be the same as of Y, so the condition it is checking for is:
(null) === (null)
which returns true
. The same applies with Undefined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With