I came across a clever null-safe property access trick in JavaScript while reading this solution to a tree-parsing problem on leetcode. It uses the OR operater (||
) to specify default values. But in this case, it also avoids throwing an exception due to accessing a property of a primitive:
(MaybeObject || 0).prop
This evaluates to undefined
, but I don't understand why, because the error should still arise, due to the order of evaluation:
- Evaluate
MaybeObject
, let's say it'sundefined
(a false value). - Evaluate the second operand of
||
, here it's0
(another a falsy value). false || false
evaluates tofalse
.- Access the
prop
property of the result of the previous computation (false
).
How is it that JavaScript does not throw an error when trying to access a non-existent property of false
?
My first intuition was that maybe the number 0
was converted to the String 'false'
, but the following expression also evaluates to undefined
:
(undefined || 0).length // => undefined, not a String of length 5
Can you help me shed some light on this?