The nullish coalescing operator

Abolfazl jamshidi
2 min readAug 10, 2023

--

When it comes to logical operators, we can get quite excited about a way to only check if a value is null or undefined. The nullish coalescing operator comes in handy in this scenario. Before we dive into how we can use it, we want to have a quick look at the &&, || operators.

// falsey values: false, null, undefined, 0 , ""

// && operator:
let nickName = "abolfazlcodes";

// if the first operand is truthy, AND returns the second operand:
let result = nickName && 0; // 0

// if the first operand is falsy, AND returns it.
// The second operand gets ignored
result = 0 && nickName; // 0

As the code represents, the AND operator will return the falsey value. The OR operator, by the way, returns the first truthy value if finds.

// || operator:
let nickName = "abolfazlcodes";

// if the first operand is truthy, OR returns that:
let result = nickName || 0; // abolfazlcodes

// if the first operand is falsy, OR will move on to find
// the truthy value
result = 0 && nickName; // abolfazlcodes

Now, it’s time to use our magic nullish operator which is used by two question marks (??). There are scenarios in which we need to cross out the 0, false and empty strings from our falsey values to check. Take a look at the code block:

// falsey values: false, null, undefined, 0 , ""
// nullish values: null and undefined

// ?? operator
let nickName = "abolfazlcodes";

// if the first oprand is a nullish value (null or undefined):
let result = null ?? nickName; // it returns the second (abolfazlcodes)

// if the first oprand is not a nullish value (including 0, false, "")
// it returns that:
result = false ?? nickName; // false
result = "" ?? nickName; // ""
result = 0 ?? nickName; // 0

Precedence

There are some points that we should consider when it comes to using these logical operators. The precedence of the ?? operator is the same as the || operator — they both equal 3 in the MDN table. Meanwhile, the && operator equals 4. So, we may need to use parentheses in expressions like this:

let width = null;
let height = null;

// calculating rectangle area: use parentheses
let area = (width ?? 100) * (height ?? 60);

// output: 6000

What if we omit the parentheses? What will happen if we try to calculate the area without considering the precedence?

// without parentheses:
let area = width ?? 100 * height ?? 60;

// in this case, * operator has higher precedence
// and it will get executed first which is not what we want:
let area = width ?? (100 * height) ?? 60;

--

--