You can use the logical 'OR' operator in place of the Elvis operator:

For example displayname = user.name || "Anonymous" .

But Javascript currently doesn't have the other functionality. I'd recommend looking at CoffeeScript if you want an alternative syntax. It has some shorthand that is similar to what you are looking for.

For example The Existential Operator

zip = lottery.drawWinner?().address?.zipcode

Function shortcuts

()->  // equivalent to function(){}

Sexy function calling

func 'arg1','arg2' // equivalent to func('arg1','arg2')

There is also multiline comments and classes. Obviously you have to compile this to javascript or insert into the page as <script type='text/coffeescript>' but it adds a lot of functionality :) . Using <script type='text/coffeescript'> is really only intended for development and not production.

Answer from Lime on Stack Overflow
Top answer
1 of 16
176

You can use the logical 'OR' operator in place of the Elvis operator:

For example displayname = user.name || "Anonymous" .

But Javascript currently doesn't have the other functionality. I'd recommend looking at CoffeeScript if you want an alternative syntax. It has some shorthand that is similar to what you are looking for.

For example The Existential Operator

zip = lottery.drawWinner?().address?.zipcode

Function shortcuts

()->  // equivalent to function(){}

Sexy function calling

func 'arg1','arg2' // equivalent to func('arg1','arg2')

There is also multiline comments and classes. Obviously you have to compile this to javascript or insert into the page as <script type='text/coffeescript>' but it adds a lot of functionality :) . Using <script type='text/coffeescript'> is really only intended for development and not production.

2 of 16
154

2020 Update

JavaScript now has equivalents for both the Elvis Operator and the Safe Navigation Operator.


Safe Property Access

The optional chaining operator (?.) is currently a stage 4 ECMAScript proposal. You can use it today with Babel.

// `undefined` if either `a` or `b` are `null`/`undefined`. `a.b.c` otherwise.
const myVariable = a?.b?.c;

The logical AND operator (&&) is the "old", more-verbose way to handle this scenario.

const myVariable = a && a.b && a.b.c;

Providing a Default

The nullish coalescing operator (??) is currently a stage 4 ECMAScript proposal. You can use it today with Babel. It allows you to set a default value if the left-hand side of the operator is a nullary value (null/undefined).

const myVariable = a?.b?.c ?? 'Some other value';

// Evaluates to 'Some other value'
const myVariable2 = null ?? 'Some other value';

// Evaluates to ''
const myVariable3 = '' ?? 'Some other value';

The logical OR operator (||) is an alternative solution with slightly different behavior. It allows you to set a default value if the left-hand side of the operator is falsy. Note that the result of myVariable3 below differs from myVariable3 above.

const myVariable = a?.b?.c || 'Some other value';

// Evaluates to 'Some other value'
const myVariable2 = null || 'Some other value';

// Evaluates to 'Some other value'
const myVariable3 = '' || 'Some other value';
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Nullish_coalescing
Nullish coalescing operator (??) - JavaScript | MDN
However, due to || being a boolean logical operator, the left-hand-side operand was coerced to a boolean for the evaluation and any falsy value (including 0, '', NaN, false, etc.) was not returned. This behavior may cause unexpected consequences if you consider 0, '', or NaN as valid values. ... const count = 0; const text = ""; const qty = count || 42; const message = text || "hi!"; console.log(qty); // 42 and not 0 console.log(message); // "hi!" and not "" The nullish coalescing operator avoids this pitfall by only returning the second operand when the first one evaluates to either null or undefined (but no other falsy values):
Top answer
1 of 10
143

For some years now it is simply

a?.b?.c
a?.b?.c ?? "default"

Check "Can I Use" for compatibility: https://caniuse.com/mdn-javascript_operators_optional_chaining,mdn-javascript_operators_nullish_coalescing


Update (2022-01-13): Seems people are still finding this, here's the current story:

  • Optional Chaining is in the specification now (ES2020) and supported by all modern browsers, more in the archived proposal: https://github.com/tc39/proposal-optional-chaining
  • babel-preset-env: If you need to support older environments that don't have it, this is probably what you want https://babeljs.io/docs/en/babel-preset-env
  • Babel v7 Plugin: https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining

Update (2017-08-01): If you want to use an official plugin, you can try the alpha build of Babel 7 with the new transform. Your mileage may vary

https://www.npmjs.com/package/babel-plugin-transform-optional-chaining

Original:

A feature that accomplishes that is currently in stage 1: Optional Chaining.

https://github.com/tc39/proposal-optional-chaining

If you want to use it today, there is a Babel plugin that accomplishes that.

https://github.com/davidyaha/ecmascript-optionals-proposal

2 of 10
95

It's not as nice as the ?. operator, but to achieve a similar result you could do:

user && user.address && user.address.postcode

Since null and undefined are both falsy values (see this reference), the property after the && operator is only accessed if the precedent it not null or undefined.

Alternatively, you could write a function like this:

function _try(func, fallbackValue) {
    try {
        var value = func();
        return (value === null || value === undefined) ? fallbackValue : value;
    } catch (e) {
        return fallbackValue;
    }
}

Usage:

_try(() => user.address.postcode) // return postcode or undefined 

Or, with a fallback value:

_try(() => user.address.postcode, "none") // return postcode or a custom string
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Nullish_coalescing_assignment
Nullish coalescing assignment (??=) - JavaScript | MDN
No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const:
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Optional_chaining
Optional chaining (?.) - JavaScript | MDN
Note: If someInterface itself is null or undefined, a TypeError exception will still be raised ("someInterface is null"). If you expect that someInterface itself may be null or undefined, you have to use ?. at this position as well: someInterface?.customMethod?.(). eval?.() is the shortest way to enter indirect eval mode. You can also use the optional chaining operator with bracket notation, which allows passing an expression as the property name:
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › objects: the basics
Optional chaining '?.'
E.g. in user?.address.street.name the ?. allows user to safely be null/undefined (and returns undefined in that case), but that’s only for user. Further properties are accessed in a regular way.
🌐
Medium
medium.com › @zayani.zied › safe-navigation-operator-optional-chaining-js-and-angular-d253431a2625
Safe Navigation Operator-Optional Chaining (JS and Angular) | by Zied ZAYANI | Medium
February 20, 2023 - The safe navigation operator, also known as Optional chaining in JavaScript is a feature that allows us to safely access properties or functions of an object without throwing an error if any of the properties in the chain are nullish (null or undefined).
🌐
Wikipedia
en.wikipedia.org › wiki › Safe_navigation_operator
Safe navigation operator - Wikipedia
1 month ago - In programming languages where the navigation operator (e.g. ".") leads to an error if applied to a null object, the safe navigation operator stops the evaluation of a method/field chain and returns null as the value of the chain expression. It was first used by Groovy 1.0 in 2007 and is currently supported in languages such as C#, Swift, TypeScript, Ruby, Kotlin, Rust, JavaScript, and others.
Find elsewhere
🌐
DEV Community
dev.to › pichardoj › optional-null-safe-in-javascript-1b7k
Optional (null-safe) in javascript - DEV Community
July 20, 2021 - This issue is not exclusive of javascript, it is present in most programming languages, so let's see how to do null-checking in some of them. ... SomeClass object; Optional.ofNullable(object) .map(obj -> obj.prop1) .map(obj -> obj.prop2) .map(obj -> obj.prop3) .orElse("SomeDefaultValue"); In kotlin (another JVM language) there are the elvis (?:) and safe-call (?.) operators.
🌐
Medium
obaranovskyi.medium.com › groovy-null-safe-operator-in-javascript-or-optional-chaining-f8f9d99e1893
Groovy null-safe operator in JavaScript (or Optional Chaining) | by Oleh Baranovskyi | Medium
March 11, 2018 - Here is few examples: // #1 - when we need to set city for user or use default let personCity = get(person, 'address', 'city') || 'not specified'// #2 - when we don't want to use wide if condition // or try/catch block if(get(person, 'address', ...
🌐
Medium
medium.com › @gabrielairiart.gi › advanced-javascript-use-of-nullish-coalescing-and-optional-chaining-and-for-efficient-coding-7d1d3fe3eedf
Advanced JavaScript: Use of Nullish Coalescing ?? and Optional Chaining and ?. for Efficient Coding | by Gabriela Iriart | Medium
March 22, 2024 - One powerful tool in JavaScript for managing null values is the Nullish Coalescing Operator (??). This operator allows developers to provide a default value for a variable if it is null or undefined, thus ensuring that the variable has a usable ...
🌐
Onux
docs.onux.com › en-US › Developers › JavaScript-PP › Language › Reference › Expressions › safe-navigation-operator
Safe Navigation (?.) Operator | JS++ & JavaScript Documentation
The safe navigation operator applies to both existent types and ... If the object (left-hand side) of the expression evaluates to null, the null value will be returned.
🌐
Beyondjava
beyondjava.net › elvis-operator-aka-safe-navigation-javascript-typescript
Elvis Operator (aka Safe Navigation) in JavaScript and ...
Beyond Java · Sitemap · Talks & Articles · Projects · Guest Posts · About · Legalese · Statistics · (opt out) · Mastodon
🌐
freeCodeCamp
freecodecamp.org › news › javascript-optional-chaining
How to Use Optional Chaining in JavaScript
February 7, 2022 - Optional chaining is a safe and concise way to perform access checks for nested object properties. The optional chaining operator ?. takes the reference to its left and checks if it is undefined or null. If the reference is either of these nullish values, the checks will stop and return undefined.
🌐
Bram.us
bram.us › 2017 › 01 › 30 › javascript-null-propagation-operator
ESNext: JavaScript “Optional Chaining Operator”
Now enter the “Optional Chaining Operator” ?. which provides us with a very elegant syntax and fail-safe approach to the issue described above: const firstName = message.body?.user?.firstName || 'Stranger'; Whenever the expression to the left of the ?. operator evaluates to either null or undefined the whole expression it belongs to will evaluate to undefined, thus falling back to the default defined using the ||: const firstName = message.body?.inexistent?.firstName || 'Stranger'; In the example above message.body?.inexistent evaluates to undefined.
🌐
Reddit
reddit.com › r/javascript › [askjs] achieve some kind of null safety with js & jsdoc
r/javascript on Reddit: [AskJS] Achieve some kind of null safety with JS & JSDoc
June 5, 2024 -

I'm working on a large code base written in JavaScript (no TypeScript) and Vue.

Recently, we refactored a big chunk of our application core code and experienced some bugs due to it, which fortunately have been logged, identified and fixed. A key problem of ours was that many object accesses happened on null and undefined. I think this could have been avoided if there were some kinds of warnings when we try to access properties of an object that could be null or undefined.

We already annotated these objects in question with JSDoc which gives us the correct properties that we could access, but our IDE (PHPStorm) doesn't notify us about null access. Although there seems to be some mechanism to warn about null, like in this example:

const foo = null;
const bar = foo.baz; // -> marks foo with the message: 'foo is null'

But if we had an annotated variable defined in another context, we don't see any warning whatsoever

/**
 * @type {{baz: string}|null}
 */
const foo = null;
function accessFoo(){
    const bar = foo.baz; // just works, bar has type string now
}

Is this specific to our IDE in use? Is there any way to catch these errors? For now, we can't migrate to TypeScript (where I know that this is configurable) but ideally it would work similarly. But we would be happy with anything that makes it a bit easier for us to reason about null access.

🌐
DEV Community
dev.to › pssingh21 › safe-navigation-operator-bang-bang-bang-192j
Safe Navigation Operator? Bang! Bang Bang!! - DEV Community
March 12, 2021 - In this case, the compiler does not keep track that map.has() has been evaluated while evaluating map.get(). So the compiler can't determine if the map returns a safe value. This can also be used in terms of calling a possibly undefined function and array indexes. ... For example it could be used when using React refs. When using refs, the current value may be null if the element is unmounted. In JavaScript every value is assocaiated as either a truthy value or a falsy value. So, a bang(!) as a prefix on a value acts as a logical "not" operator on that value.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript optional chaining operator
JavaScript Optional Chaining Operator (?.)
December 17, 2023 - Therefore, before accessing the avatar property, you need to check if the user is not null using the logical operator AND: let user = getUser(2); let profile = user && user.profile;Code language: JavaScript (javascript) In this example, we confirm that the user is not null or undefined before accessing the value of user.profile property.