What in the world is Nullish Coalescing??

ES2020 introduced the nullish coalescing operator. As the name suggests nullish coalescing is used to handle null or undefined values. It is a logical operator represented with double question marks (??), that returns its right-hand side operand when its left-hand side operand is null or undefined and otherwise returns its left-hand side operand.

In the previous versions logical OR(||) operator was used for the same. Let's look into these operators and understand the difference.

Logical OR(||) Operator

Logical OR operator works well with boolean values for conditional statements, but when we use it for different data types, javascript will convert that datatype to boolean because every datatype in js is either truthy or falsy.

false, 0, -0, 0n, "" (empty string), null, undefined, and NaN are all considered as falsy and any values other than these are truthy in JS.

When a logical OR operator work with falsy values like null and undefined it behaves similar to the nullish coalescing operator but when an empty string or 0 is passed it will convert them to false and that's where the problem arises. In these cases, it will return the default value.

Syntax

leftOperand || rightOperand

Examples

const qty = 1 || 4:
// output 1

const qty = null || 4:
// output 4

const qty = 0 || 5;
// output: 5 -- Here the output should have been 0 but it returns 5 as it treat 0 as falsy value.

Nullish Coalescing (??) Operator

It returns the right-hand side operand when its left-side operand is either null or undefined. It only treats these values as falsy and thus it resolves the problems with logical OR operator.

Syntax

leftOperand ?? rightOperand

Examples

const qty = 1 ?? 4:
// output 1

const qty = null ?? 4:
// output 4

const qty = 0 ?? 5;
// output: 0 -- Here 0 is treated as a true value and thus output is 0.

const name = "" ?? "phil"
// output: "" -- Here "" (empty string) is treated as a true value and thus output is an empty string

Summary

TopicNullish Coaleasing Operator(??)Logical OR (ll) Operator
DefinitionIt returns its right-hand side operand when its left-hand side operand is null or undefined and otherwise returns its left-hand side operand.It returns its right-hand side operand when its left-hand side operand is null, undefined, 0, empty string or any other falsy values which causes a problem.
SyntaxleftOperand ?? rightOperandleftOperand ll rightOperand
Exampleconst qty = 0 ?? 5; // output: 0 -- Here 0 is treated as a true value and thus output is 0.const qty = 0 ll 5; // output: 5 -- Here the output should have been 0 but it returns 5 as it treat 0 as falsy value.