Home > Article > Web Front-end > How do you handle null values in JavaScript?
The Elvis and Safe Navigation Operators in JavaScript
The Elvis operator, also known as the null-coalescing operator, is a convenient way to return a default value when an expression evaluates to null or false. For instance:
<code class="javascript">const displayName = user.name || "Anonymous";</code>
In JavaScript, you can also use the logical OR operator to achieve similar results:
<code class="javascript">const displayName = user.name ? user.name : "Anonymous";</code>
While JavaScript doesn't currently have a dedicated safe navigation operator, you can use conditional logic to avoid NullPointerExceptions:
<code class="javascript">const user = User.findById("admin"); const streetName = user ? (user.address ? user.address.street : null) : null;</code>
Alternative Syntax: CoffeeScript
If you're looking for a more concise syntax, consider using CoffeeScript. It provides several shorthands that resemble the Elvis and safe navigation operators:
Existential Operator: Returns the value of a property if it exists, otherwise returns undefined.
<code class="coffeescript">zip = lottery.drawWinner?().address?.zipcode</code>
Function Shortcuts: Allows you to omit parentheses for functions.
<code class="coffeescript">func 'arg1','arg2' // equivalent to func('arg1','arg2')</code>
Sexy Function Calling: Provides a more concise way to call functions with multiple arguments.
<code class="coffeescript">func 'arg1','arg2' // equivalent to func('arg1','arg2')</code>
CoffeeScript adds a wide range of functionality to JavaScript, including multiline comments, classes, and more. It can be compiled into JavaScript or inserted into a page using