Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Explain If Type(x) is Undefined, return true. If Type(x) is Null, return true

Tags:

javascript

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:

  1. If Type(x) is different from Type(y), return false.
  2. If Type(x) is Undefined, return true.
  3. If Type(x) is Null, return true.
  4. If Type(x) is Number, then
    1. If x is NaN, return false.
    2. If y is NaN, return false.
    3. If x is the same Number value as y, return true.
    4. If x is +0 and y is -0, return true.
    5. If x is -0 and y is +0, return true.
    6. Return false.
  5. 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.
  6. If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
  7. 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.

like image 614
Ray Cheng Avatar asked Feb 23 '23 11:02

Ray Cheng


2 Answers

Before that it says:

where x and y 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.

like image 95
Quentin Avatar answered Feb 25 '23 00:02

Quentin


My interpretation is one of reading the spec as a formal proof, having the numbers 2 and 3 dependent on the first rule:

  1. 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

like image 41
Steve Lewis Avatar answered Feb 25 '23 00:02

Steve Lewis