Have you confused between ??
and ||
in javascript. Majority of the people think that both are same but both are not same. Purposes are different.
||
is an OR operator and ??
is a nullish coalescing operator.
Whats the difference ?
About ||
This is an OR operator. OR operator will check for operands and returns truthy operand if any of the operand is valid or truthy.
Here are the examples:
true || false // true because first operand is true
1 || false // 1 because first operand is 1 i.e truthy
false || "Hello" // "Hello" because second operand is "Hello" i.e truthy
Looks good then what is the problem with ||
and why we need ??
.
Look at this snippet
0 || 1 // 1 In javascript 0 is falsy value so || operator will ignore it.
"" || 1 // 1 because "" is empty string in JS empty string is falsy value.
But 0 is not a falsy value it is a number. Setting a variable to 0 dosen't mean that setting falsy value to variable. When there are no characters in a string we call it empty string. If a string dosen't have chars it dosen't mean its a falsy.
With ||
we have this problem. Every time when we deal with the scenarios mentioned above we have to write extra conditions.
Example:
From backend service we are receiving student marks. Assume for some students there are extra subjects for the students who don't have extra subjects API giving null or undefined value for those subjects. In frontend if the subject marks are null or undefined we have to show "NA". We can write like this
Object.keys(marks).forEach(subject => {
console.log(subject + " -> " + (marks[subject] || "NA")
})
But we have a problem with the above code what is subject marks or 0 ?
We have to modify the code like this
Object.keys(marks).forEach(subject => {
console.log(subject + " -> " + (marks[subject] || marks[subject]) == 0 ? marks[subject] : "NA"))
})
So we now we have a solution for this problem in javascript to avoid these scenarios i.e nullish coalescing operator.
Nullish coalescing operator will check operands and gives non nullish value. Look in to the following snippet.
0 ?? 1 // 0
"" ?? 1 // ""
0 ?? null // 0
null ?? 1 // 1
As 0 and "" are not nullish values it will consider those.
What values are nullish ?
null
undefined
Cheers,
Happy coding !!
Top comments (0)