Operator Precedence of Nullish Coalescing and Ternary Operators
The Problem
Today, I learned that you simply cannot combine the nullish coalescing operator (??
) with the ternary operator (? :
) without being cautious. Or rather, you can, but the evaluation may lead to results you don't expect.
Important Note: The issue I faced here was largely due to my incomplete knowledge of operator precedence. If you’re not familiar with how JavaScript decides which operations to evaluate first, you can easily end up with surprising behaviors. Understanding operator precedence is crucial for writing reliable code—and everyone should take time to learn it thoroughly!
Example
1let result = 10 ?? true ? 20 : 30;
This is a simplified example, but I initially expected that since 10
is not a nullish value (null
or undefined
), the statement would evaluate to 10
.
However, it does not. It actually evaluates to 20
.
Why is That?
This happens because the nullish coalescing operator (??
) has a higher operator precedence than the conditional (ternary) operator (? :
). This means the ??
operator executes first.
The example essentially evaluates as follows:
1let result = (10 ?? true) ? 20 : 30; // => 10 ? 20 : 30
Since 10
is a truthy value, the ternary operation (10 ? 20 : 30
) evaluates to 20
.
The Solution
To achieve the expected result of 10
, you need to wrap the ternary operation in parentheses:
1let result = 10 ?? (true ? 20 : 30); // result = 10
The Importance of Operator Precedence
As mentioned, the unexpected outcome happened because the nullish coalescing operator was evaluated before the ternary operator, leading to a different result than anticipated. This highlights the significance of thoroughly understanding how JavaScript handles operator precedence. By knowing which operations occur first, you can write more predictable and maintainable code.
Summary
Combining the nullish coalescing operator with the ternary operator in JavaScript can lead to unexpected results due to operator precedence. The nullish coalescing operator has a higher precedence and is executed first. To ensure the correct result, wrap the ternary operation in parentheses. Most importantly, make sure to deepen your knowledge of operator precedence to avoid similar pitfalls in the future!