javascriptoptional-chainingecmascript-2020

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?


Solution

  • 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);