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.

Join the Conversation

2 responses from 2 others.

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.