Dong
Dong

Reputation: 309

Is there an equivalent of optionalChaining in Javascript ES2020?

As we know, ES2020 supports optionalChaining. For example, we can write codes like: let x = {a:{b:'c'}}; console.log(x?.a?.b); and we will get 'c'.

But in some cases, we may want to use the expression like x[a][b] rather than x.a.b. Can we use something like x?[a]?[b] to evaluate the validation of each chained object?

Upvotes: 0

Views: 63

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

The syntax is the same for brackets notation:

 x?.[a]?.[b]

Example:

const x = {a:{b:'c'}};
const a = 'a';
const b = 'b';

const result = x?.[a]?.[b];

console.log(result);

Upvotes: 1

Related Questions