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.

Top comments (0)