0

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:

  1. Evaluate MaybeObject, let's say it's undefined (a false value).
  2. Evaluate the second operand of ||, here it's 0 (another a falsy value).
  3. false || false evaluates to false.
  4. 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?

MikaelF
  • 3,518
  • 4
  • 20
  • 33
  • Your assumption in #3 is incorrect. `false || 0` evaluates to `0`, not `false` - therefore `(0).prop` is undefined – chazsolo Apr 01 '19 at 19:16
  • 1
    More relevant questions: https://stackoverflow.com/questions/2100758/javascript-or-variable-assignment-explanation https://stackoverflow.com/questions/2802055/what-does-the-construct-x-x-y-mean basically `||` will return either the first truthy value or the last value. It doesn't convert into a boolean. – VLAZ Apr 01 '19 at 19:19
  • ((false).prop) returns undefined in chrome dev tools console...... curiouser and curiouser.... ( removing any logical operators complications from your main question) – Bob Apr 01 '19 at 19:20
  • 1
    Logical operatos don't always return boolean value. *"&& and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they will return a non-Boolean value"* (Even if it did, it wouldn't make a difference in your case. `(undefined || false).prop` returns `undefined` – adiga Apr 01 '19 at 19:20
  • might be because booleans can be objects as well as primitives (eg new Boolean(false) ) and it may be interpreted as an object if a property requested and then it's not there so "undefined"..... – Bob Apr 01 '19 at 19:27
  • 1
    see https://stackoverflow.com/a/10225638/4779501 ( lots of similar but no authoritative refs found so far ) – Bob Apr 01 '19 at 19:41

0 Answers0