Reputation: 82351
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
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
Reputation: 816462
What values of
someOtherVar
will causesomeVar
to betrue
?
Only null
and undefined
.
The algorithm in the spec is relatively straight forward:
- If
Type(x)
is the same asType(y)
, then Return the result of performing Strict Equality Comparisonx === y
.- If
x
is null andy
is undefined, return true.- If
x
is undefined andy
is null, return true.- If
Type(x)
is Number andType(y)
is String, return the result of the comparisonx == ToNumber(y)
.- If
Type(x)
is String andType(y)
is Number, return the result of the comparisonToNumber(x) == y
.- If
Type(x)
is Boolean, return the result of the comparisonToNumber(x) == y
.- If
Type(y)
is Boolean, return the result of the comparisonx == ToNumber(y)
.- If
Type(x)
is either String, Number, or Symbol andType(y)
is Object, return the result of the comparisonx == ToPrimitive(y)
.- If
Type(x)
is Object andType(y)
is either String, Number, or Symbol, return the result of the comparisonToPrimitive(x) == y
.- 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