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

Answer from basicdays on Stack Overflow
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › objects: the basics
Optional chaining '?.'
... Please note: the ?. syntax makes optional the value before it, but not any further. 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.
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
Nullish coalescing operator (??) - JavaScript | MDN
The nullish coalescing operator treats undefined and null as specific values. So does the optional chaining operator (?.), which is useful to access a property of an object which may be null or undefined. Combining them, you can safely access a property of an object which may be nullish and ...
🌐
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.
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 › 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:
🌐
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.
Find elsewhere
🌐
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 ... 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 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, ...
🌐
Designcise
designcise.com › web › tutorial › does-javascript-have-safe-navigation-operator
Does JavaScript Have Safe Navigation Operator? - Designcise
August 22, 2021 - It evaluates an expression from left-to-right; when/if the left operand evaluates to a nullish value, it stops the execution of the entire chain and short-circuit evaluates the expression to undefined.
🌐
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.
🌐
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 - A long time ago I was working as Groovy developer and I found that language pretty cool :) . From the beginning I understood that groovy has many great syntax sugar features and today we gonna to talk about one of them, it’s called null-safe operator, and it looks like this ?. (I heard that some people also calling it as Optional Chaining) Now you probably say that “it’s great that groovy has it, but what about JavaScript”. So we have the following plan:
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript optional chaining operator
JavaScript Optional Chaining Operator (?.)
December 17, 2023 - let user = getUser(1); let profile = user.profile;Code language: JavaScript (javascript) However, if you pass the id that is less than or equal to zero or the id doesn’t exist in the database, the getUser() function will return null. Therefore, before accessing the avatar property, you need to check if the user is not null using the logical operator AND:
🌐
Folkstalk
folkstalk.com › tech › javascript-safe-operator-with-code-examples
Javascript Safe Operator With Code Examples
Use the safe navigation operator ( ?. ) to replace explicit, sequential checks for null references.Use the Safe Navigation Operator to Avoid Null Pointer Exceptions · This example first evaluates a , and returns null if a is null.
🌐
freeCodeCamp
freecodecamp.org › news › javascript-advanced-operators
Advanced JavaScript Operators – Nullish Coalescing, Optional Chaining, and Destructuring Assignment
January 4, 2024 - Hi Everyone! In this article, I'm going to teach you how to use three advanced JavaScript operators: the Nullish Coalescing, Optional Chaining, and Destructuring Assignment operators. These three operators will help you write clearer and less error-p...
🌐
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.
🌐
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