DEV Community

Cover image for Nullish coalescing operator ??
Ezekiel Ilori
Ezekiel Ilori

Posted on

Nullish coalescing operator ??

It is used when you want to return a default value if left-hand-side value/condition is null or undefined only

Example:

const getVal = (target) => {
 return target.value ?? 'default';
};

console.log(
 getVal({ value: 'Hello'}),
 getVal({ value: 0 })
 getVal({ value: ''}),
 getVal({})
);

Output:

Hello 0 default

It is different from Logical-Or operator, ||

|| checks if the left-hand value/condition is falsy

Example:

const getVal = (target) => {
  return target.value || 'default'
};

console.log(
  getVal({ value: 'Hello'}),
  getVal({ value: 0 }),
  getVal({ value: ''}),
  getVal({})
);

Output:

Hello default default default

DIFFERENCE

?? returns default when left-hand-value/condition is null or undefined only.

|| returns default when left-hand-value/condition is falsy.

Note: Older browsers may need a polyfill

Top comments (0)