DEV Community

Mohamed Idris
Mohamed Idris

Posted on

Insights into Null Coalescing Operator and If Conditions for Faster Coding

I thought the null coalescing operator was limited to something like:

null ?? 'show this value';
undefined ?? 'show that value';
Enter fullscreen mode Exit fullscreen mode

However, it surprised me that we can actually chain and use it multiple times, as in:

null ?? undefined ?? 'show this value';
Enter fullscreen mode Exit fullscreen mode

While this chaining capability exists, it's not always recommended. Typically, for the sake of readability, a more explicit 'if' condition would be preferable. But, it might be handy and preferable for a concise single line of code.

And speaking of 'if' condition, I also learned that we could use a single line of code for both 'else if' and 'else' (without curly braces), as demonstrated in the image below.

code example

Credits to Jeffrey Way in his great series about PHP, but it's really more than that.

Neon image

Build better on Postgres with AI-Assisted Development Practices

Compare top AI coding tools like Cursor and Windsurf with Neon's database integration. Generate synthetic data and manage databases with natural language.

Read more →

Top comments (0)

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay