Languages
[Edit]
EN

JavaScript - ?. operator and optional chaining in ES2020

4 points
Created by:
Marcin
2535

In this short article we would like to show how to use Optional Chaning in JavaScript.

ES2020 introduced ?. operator that gives possibility to avoid testing if property exists and return imidatelly undefined value. The operator can be used with properties, arrays and functions.

Syntax looks following way:

SyntaxDescription
obj?.propobject property access
obj?.[expr]object property access with brackets
arr?.[index]array item access by index
func?.(args)function calling

Simple example:

// ONLINE-RUNNER:browser;

// accepted: uninitialised, undefined or null

var obj;
var arr = undefined;
var func = null;

console.log(obj?.items);        // undefined
console.log(obj?.['name']);     // undefined
console.log(arr?.[10]);         // undefined
console.log(func?.('Hello!'));  // undefined

More complex cases: 

// ONLINE-RUNNER:browser;

var obj = {
    items: undefined,
    func: null // or undefined
};

console.log(obj.items);               // undefined
console.log(obj.items?.[10]);         // undefined

console.log(obj.members?.name);       // undefined
console.log(obj.members?.['name']);   // undefined

console.log(obj.func?.('Hello!'));
console.log(obj.print?.('Hello!', 'How are you?'));  // undefined

// long property path:

console.log(obj?.very?.['long']?.path?.to?.[5]?.property?.action?.(1, 2, 3));  // undefined

Callback example:

// ONLINE-RUNNER:browser;

function ajax(onSuccess, onError) {
    try {
        // simulated request error:
        throw new Error('Timeout error!');
    } catch(e) {
        onError?.('Request error!');
    }
}

ajax(function(data) {
    console.log(data);
});

// this code returns nothing because on onError function is not defined

 

Hey 👋
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.