What is the difference between ??
and ||
in JS
const a = {}
const b = a.name ?? 'varun 1'
console.log(b)
const d = a.name || 'varun 2'
console.log(d)
In the above code they both work the same. I know ||
is OR i.e if the first statement is false
then set the value for the next one. Is it same for ??
?
The main difference is that nullish coalescing(??)
operator will only give the result as the right operand only if the left operand is either null
or undefined
.
Whereas the OR(||)
operator will give the result as right operand for all the falsy values of the left operand.
Below are some examples
0
as inputconst a = 0;
// a || 10 --> Will result in 10, as || operator considers 0 as falsy value and resulting the right side operand
console.log(`a || 10 = ${a || 10}`);
// a ?? 10 --> Will result in 0, as ?? operator considers 0 as truthy value and resulting the left side operand
console.log(`a ?? 10 = ${a ?? 10}`);
''
as inputconst a = ''
console.log(`a || "ABC" = ${a || "ABC"}`); // ABC
console.log(`a ?? "ABC" = ${a ?? "ABC"}`); // ''
null
as inputconst a = null;
console.log(`a || 10 = ${a || 10}`); // 10
console.log(`a ?? 10 = ${a ?? 10}`); // 10
undefined
as inputconst a = {}
// Here a.name will be undefined, hence both of the operands results the right side operand
console.log(`a.name ?? 'varun 1' = ${a.name ?? 'varun 1'}`); // 'varun 1'
console.log(`a.name || 'varun 2' = ${a.name || 'varun 2'}`); // 'varun 2'
const a = {name: ''}
// Here a.name will be '', then
// ?? will result ''
console.log(`a.name ?? 'varun 1' = ${a.name ?? 'varun 1'}`);
// || will result in 'varun 2'
console.log(`a.name || 'varun 2' = ${a.name || 'varun 2'}`);
false
as inputconst a = false;
console.log(`a || 10 = ${a || 10}`); // 10
console.log(`a ?? 10 = ${a ?? 10}`); // false
As mentioned above, both the operators behave similarly when the input is either null
or undefined
. The real difference we'll get to see when we provide falsy
values such as 0
, ''
, false
, NaN
.