Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

JavaScript - ?. operator and optional chaining in ES2020

0 contributions
4 points

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

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more