Home >Web Front-end >JS Tutorial >How Can You Handle Null Values and Access Object Properties Safely in JavaScript?
Elvis and Safe Navigation Operators in JavaScript
In Java, Elvis (?:) and Safe Navigation (?.) operators provide convenient ways to handle null values and access object properties safely. While JavaScript doesn't offer these exact operators, alternative approaches exist.
Elvis Operator (?:)
To achieve the functionality of the Elvis operator, you can use the logical 'OR' operator (||):
<code class="js">const displayName = user.name || "Anonymous";</code>
Safe Navigation Operator (?.)
JavaScript doesn't currently have an equivalent to the Safe Navigation operator. However, you can use the following pattern instead:
<code class="js">const streetName = user?.address?.street;</code>
If any part of the chain (e.g., user, address, street) is null, streetName will be set to null. This method avoids potential NullPointerExceptions.
Alternative Solutions
If you desire the syntax of Elvis and Safe Navigation operators, consider using CoffeeScript. It offers similar shorthand:
Existential Operator
<code class="coffee">zip = lottery.drawWinner?().address?.zipcode</code>
Function Shortcuts
<code class="coffee">() -> // equivalent to function(){}</code>
Sexy Function Calling
<code class="coffee">func 'arg1', 'arg2' // equivalent to func('arg1', 'arg2')</code>
While CoffeeScript syntax might be more expressive, it requires compilation or insertion as '