javascriptoptional-chaining

Optional Chaining in JavaScript returns undefined instead of null when the variable to be tested is null


So, I am reading optional chaining in JavaScript and a question popped into my head.

Consider the code below:

let person = null
let street = person?.street // returns undefined

My question is that, if the variable person is null to begin with, then why is doing optional chaining result to setting the variable as undefined and not null?

If the person was undefined, then I guess, for me, setting it to undefined is reasonable because the variable is of course undefined, like the below:

let person
let street = person?.street // returns undefined 

PS: I'm sorry if this is a stupid question, I'll delete it if someone agrees. :)

PPS: If this question is duplicated, pls drop the link and I'll give it a go. Thank you, very much.


Solution

  • An optional chain does not evaluate to the nullish value on which the property was accessed, but to undefined - just like you get undefined when a property does not exist in an object.

    Conceptually, think of person?.street not as

    person && person.street
    

    but rather as

    (person ?? {}).street
    

    Though accurately (especially when chained further, since it does short-circuit instead of evaluating the rest of the chain) it's really

    person != null ? person.street : undefined
    

    See also the FAQ on the optional chaining proposal:

    Why does (null)?.b evaluate to undefined rather than null?

    Neither a.b nor a?.b is intended to preserve arbitrary information on the base object a, but only to give information about the property "b" of that object. If a property "b" is absent from a, this is reflected by a.b === undefined and a?.b === undefined.

    In particular, the value null is considered to have no properties; therefore, (null)?.b is undefined.