Search code examples
javascriptoperatorsnullish-coalescing

Is this an appropriate use of chained nullish operators?


the docs say that the nullish operator (??) is the 5th lowest precedence in operation.

I am trying to use them in this manner

const accountNumber = optionsA?.accountNumber ?? optionB?.accountNo ?? '7202705382';

which I hope to mean

assign accountNumber in descending order precedence:

  • optionsA?.accountNumber
  • optionB?.accountNo
  • '7202705382'

I am concerned because I want to ensure both that the order is left to right and that the elvis operators in the objects in the first two items do not interfere with the nullish operators valuations or precedence.

Is this the most appropriate way to do this assignment for clarity and terseness in Javascript?


Solution

  • I find it helpful to think of it in normal or even slang terms.

    Knock knock, optionsA?.accountNumber ... ? Are you there? Are you something that isn't nullish...? If so, you're now accountNumber!

    If not, let's go knock on optionB?.accountNo's door. If optionB?.accountNo answers the door (if its not nullish), then IT is now accountNumber

    Otherwise, you gotta settle for the '7202705382'

    So is it ok? Yea, it will work. But...

    All that being said (and this is totally based on my experience seeing other people's code over the years in libraries and other codebases where I've worked), I strongly recommend not doing this. It can make readability SUPER difficult. In my mind, it's akin to nested ternaries, which aren't going to make you the most loved dev in the world.