skip to Main Content

In JS, for simple variables we can do like x?.foo

Can I do this for array too?

a[0]?.foo

3

Answers


  1. Yes, altough your array may not be null, you don’t know if an item with the index 0 exists. However, the ? operator only accesses the property foo if the expression before evaluates something that is not null or undefined.

    Example

    var x = [];
    
    console.log(x[0]?.foo); // undefined
    console.log(x[0].foo); // error
    
    x = [{foo: 1}];
    
    console.log(x[0]?.foo); // 1
    console.log(x[0].foo); // 1
    

    Keep in mind that accessing an array at an index without knowing if that index exists is risky and should not be done unless really needed.

    Also, try testing before asking simple questions like these.

    Login or Signup to reply.
  2. Yes, you can use this.

    I feel you should at the very least try and do this in an online js-sandbox tool before asking these simple questions.

    // objects
    const items0 = {foo: 'bar'};
    console.log(items0?.foo)
    
    // arrays
    const items1 = [{foo: 'bar'}];
    console.log(items1[0]?.foo)
    
    // functions
    const items2 = () => ({ foo: 'bar' });
    console.log(items2()?.foo)
    Login or Signup to reply.
  3. It is possible to use the optional chaining operator with an array, you just need to add a dot before calling the index

    a?.[0]?.foo
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search