JavaScript “Null Propagation Operator“

Earlier today I was delighted to see that the “Null Propagation Operator” in JavaScript has entered stage-1. This little gem – which I know from Coffeescript – is a real timesaver, and is something I’ve been looking forward to.

Stage-1?

💁‍♂️ The TC39 Committee has a 5 stage process in place, ranging from stage-0 to stage-4, by which it develops a new language feature. Stage-1 is the proposal phase.

Without the “Null Propagation Operator” one has to reside to an if statement or Short-Circuit Evaluation in order to access specific key from a nested object:

const message = {
  body: {
    user: {
      firstName: 'Bramus',
      lastName: 'Van Damme',
    },
  },
};

const firstName = (message.body && message.body.user && message.body.user.firstName) || 'Stranger');

Shouldn’t that return true?

💁‍♂️ The reason that this works it because of JavaScript returning the last encountered value – and not a boolean – when using Short-Circuit Logic.

When not using this kind of thing, an error would be encountered in case an inexistent object/key would be accessed:

const thisWillFail = message.body.inexistend.firstName;

// --> "Cannot read property 'firstName' of undefined"

So, where exactly does this proposed operator come into play? Well, the “Null Propagation Operator” provides us with a very elegant syntax and fail-safe approach to this:

const firstName = message.body?.user?.firstName || 'Stranger';

Here’s to hoping that this one reaches stage-4 any time soon. As far as I can tell this is not in Babel (yet) the Babel folks are working on it.

Elsewhere ,

One Response to JavaScript “Null Propagation Operator“

  1. Pingback: ESNext Proposal: The Pipeline Operator | Bram.us

Leave a Reply

Your email address will not be published. Required fields are marked *