BY Simmi Kava15 Jun 2021 Edit
JavaScript: Optional Chaining Operator (?.)

Optional Chaining Operator (?.)


This operator allows you to read the value of property situated deep within a chain of connected objected without the need to check if each reference in the chain is valid or not.

Difference between ?. and . chaining operator

. chaining operator throws an error if a reference is null or undefined.

?. will return undefined if a reference is null or undefined.

The optional chaining operator comes handy when you are evaluating an object and unsure which all properties of the object are required.

Can we use ?. on undefined root object?

Yes

Can we use ?. on root object which is not declared?

No

Syntax

obj.val?.prop

obj.val?.[expr]

obj.arr?.[index]

obj.func?.(args)

Examples

const i = undefined;
const j = {val: 0};
const c = {};
c[undefined] = 11;
const k = [22];


console.log(i?.[i?.j]); //undefined
console.log(c?.[i?.j]); //11
console.log(k?.[j?.val]); //22

Optional Chaining - Method Call Example

var a = {};

var b = 1;

function add() {
    b++;
    return b;
}

console.log(a?.method?.(add())); //undefined 
console.log(b); //1

console.log(a.method?.(add())); //undefined
console.log(b); //1

Optional Chaining Index Example

var a = null;

var b = 1;

function add() {
    b++;
    return b;
}
var n = a?.[add()];
console.log(n); //undefined
console.log(b); //1

Keep Learning!

BY Simmi Kava
LikeCommentSave
LikeCommentSaveShare
0
Categories
General
YantraJS
Developer Guides
Tutorials
Web Atoms Updates

POPULAR POSTS
17 Mar 2021
LATEST ACTIVITY
Simmi Kava
commented this post.
Simmi Kava
liked this post.
Show more
ARCHIVES
2024
2023
2022
2021
TAGS
javascript (56)
developer (25)
javascriptdeveloper (16)
Xamarin.Forms (16)
Html (14)
typescript (12)
webatoms (12)
xamarin (11)
coding (10)
web-atoms (10)
arrays (9)
android (8)
javascript-developer (8)
csharp (7)
dotnet (7)
css (6)
update (6)
dotnet-standard (5)
function (5)
iOS (5)
methods (4)




Web Atoms: JSX (TSX + TypeScript) for Xamarin.Forms, Hot Reload Your App in Production Environment

PlaygroundSamples Repository