The ‘??’ operator nobody ever heard of

Dhiman Das
2 min readMay 9, 2021

--

Let me start with the word ‘why’. So why do we need this operator?

Let’s say you have a variable which holds an integer value. Now you want to check for a condition that if that variable is not ‘undefined’ or ‘null’ then you want to assign that variable to an another variable. And to solve this problem you may want to use the famous ‘||’ operator.

OR operator

If you have noticed the above code snippet, we were expecting the second output as ‘0’ but it was showing ‘undefined’ and which is not strange for me as OR operator always returns the right hand side, if left hand side is any ‘falsy’ value. And as we already know that ‘0’ is considered as a falsy value. So to solve the above problem, we can use this beautiful operator called Nullish coalescing operator.

Nullish coalescing operator

Why not a little bit of definition: The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. (Credit: developer.mozilla.org)

Thank you for investing your time…

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Dhiman Das
Dhiman Das

Written by Dhiman Das

A software developer, who also loves to read self-help book, love to do cycling, love to play music and also entered into the world of content writing.

No responses yet

Write a response