It was proposed back in 2018 (Read Proposal) and everyone was waiting for it to be launched finally the wait is over and with ES2020 we can use this Nullish Coalescing operator and it is extremely helpful
WHAT IS NULLISH COALESCING OPERATOR?
The nullish coalescing operator (
??) is a logical operator that returns the results of the right-hand-side expression if the left-hand-side expression is either
leftExpr ?? rightExpr
const name = null ?? 'Kashan Haider'; console.log(name); // expected output: "Kashan Haider" const Score = 0 ?? 42; console.log(Score); // expected output: 0 const myBool= false??'Yes'; console.log(myBool); // expected output: false
COMPARING WITH ‘OR’ ( || ) OPERATOR:
From the examples above you may think that they work similarly but NO, They both works differently and in some cases, the result is completely opposite, The examples below will clear this doubt for you
let name; //variable name is never assigned any value so it is undefined. let optionalName= name || 'defaultName'; let optionalName= name ?? 'defaultName'; // expected output: 'defaultName'
In the example above you’ll get the same result because the variable
undefined , It is because the OR operator is a boolean operator and for OR operator (
'' ) all these are falsy values. that is why the OR operator will return the string
'DefaultName' but the NULLISH COALESCING operator works only with
undefined so let’s take another example how’ll it work if the variable is not
let num = NaN //here variabale num is NaN which is a falsy value for || operator but ?? works only with null and undefined let defaultNumber = num ?? 3 // expected output: NaN let myBool = false ?? true // expected output: false
Leave a Comment