Null Propagation Operator proposal for JavaScript

At it’s January meeting, TC39 (essentially the standards body responsible for JavaScript) heard a proposal for some syntactical sugar that really excites me.  It’s called the Null Propagation operator and allows code that looks like

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

to become code that looks like

const firstName = message.body?.user?.firstname || 'default';

Essentially, it allows for eliminating lots of checks to ensure multilevel JavaScript objects are properly defined. This reminds me a bit of the null coalesce operator in PHP as  it allows for easier to read code. It needs to be balanced so these languages don’t turn into Perl filled with secret operators.

The proposal is now in stage 1 which means that TC39 “expects to devote time to examining the problem space, solutions and cross-cutting concerns”. It’s still early to get excited about this, but this is one of those pieces of syntactical sugar that make writing code easier.

2 thoughts on “Null Propagation Operator proposal for JavaScript”

  1. Context from the rest of the programming world:

    Ruby added the safe navigation operator in 2.3 with syntax `object&.method` and it’s a great convenience. Kotlin has a similar safe call operator, which uses a different sigil, `object?.method`, but I don’t find much use for it because Kotlin also has tons of other null safety features to minimize the effect of null values all around: https://kotlinlang.org/docs/reference/null-safety.html

Leave a Reply

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