Home >Web Front-end >JS Tutorial >Can Javascript\'s Ternary Operator Replace Null-Coalescing Operators?
Javascript's Ternary Conditional Operator as an Alternative to Null-Coalescing Operators
In Javascript, the logical "OR" (||) operator can be used as a rudimentary null-coalescing operator. For instance, to assign a default value to the displayName variable when user.name is null or false:
<code class="javascript">displayName = user.name || "Anonymous";</code>
However, Javascript does not natively support the safe navigation operator (?.) found in other languages.
Alternative Syntax with CoffeeScript
If you seek the expressiveness of Elvis operators and safe navigation, consider using CoffeeScript as an alternative to Javascript. It offers several shorthand notations to achieve similar effects:
Elvis Operator Equivalent:
<code class="coffeescript">displayName = user?.name || "Anonymous"</code>
Safe Navigation Operator Equivalent:
<code class="coffeescript">streetName = lottery.drawWinner?().address?.zipcode</code>
Additional CoffeeScript Features:
Note: While CoffeeScript can enhance expressiveness, it requires compilation or invocation via