Vaccano
Vaccano

Reputation: 82351

What coerces from a null compare in JavaScript?

If I have this JavaScript

var someVar = someOtherVar == null;

What values of someOtherVar will cause someVar to be true?

Note: From what I have read, if someOtherVar is undefined then someVar will be true. But I am changing a lot of my code to use this style of comparison, and I want to be sure that nothing else will result in a truthy statement (besides null and undefined).

Upvotes: 1

Views: 79

Answers (2)

Egor Stambakio
Egor Stambakio

Reputation: 18136

Looks like only null and undefined indeed:

const arr = ['string', true, false, 0, null, undefined, NaN, {}, [], 4, -1, -0];

const r = arr.map((e,i) => {
    return { i, e, bool: e == null }
}).filter(e => e.bool);

// return elements which result in 'null'
// i: index inside initial array 'arr'

console.log(JSON.stringify(r, null, 2));

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816462

What values of someOtherVar will cause someVar to be true?

Only null and undefined.

The algorithm in the spec is relatively straight forward:

  1. If Type(x) is the same as Type(y), then Return the result of performing Strict Equality Comparison x === y.
  2. If x is null and y is undefined, return true.
  3. If x is undefined and y is null, return true.
  4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
  5. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
  6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
  7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
  8. If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
  9. If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.
  10. Return false.

Step 1 handles the case null == null. Step 2 and 3 handle the cases null == undefined and undefined == null. Step 6 and 7 handle the cases where the other value is a boolean, so then you end up comparing a number against null. Since null is not an object, number, string, boolean or symbol, non of the other steps apply, so false is returned (step 10).


What coerces from a null compare in JavaScript?

Only if the other value is a boolean it would be coerced to a number, so you end up comparing either 0 == null or 1 == null, both of which are false.

In all other case, no type coercion is happening (nothing is coerced to null and null is not coerced to any other data type).

Upvotes: 5

Related Questions