0

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?

Progman
  • 16,827
  • 6
  • 33
  • 48
Dong
  • 269
  • 1
  • 3
  • 10

1 Answers1

1

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);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209