The ‘??’ operator nobody ever heard of
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.
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.
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
undefined, and otherwise returns its left-hand side operand. (Credit: developer.mozilla.org)
Thank you for investing your time…