Search code examples
javascriptoptional-chaining

Using optional chaining with array.entries


Just trying to understand optional chaining and unsure if it can be used in the following situation with .entries, that is:

for (const [index, val] of Array.from(myArray)?.entries()) {
  if (val.status === 1) {
      . . . 
       . . . 
  }
}

I basically don't want to proceed if myArray is empty.


Solution

  • If you look for a short null check, I think your problem is not from Array.from but it's from myArray variable. If myArray is undefined, Array.from(myArray)?.entries() will throw an error

    const myArray = undefined
    const entries = Array.from(myArray)?.entries() //throw an error
    

    enter image description here

    If you want to overcome this, you need to use short circuit evaluation to assign the default value [] whenever myArray is undefined or null

    const myArray = undefined
    const entries = Array.from(myArray || []).entries() //working!
    

    enter image description here

    If myArray is already an array (or possibly an undefined value), you can get rid of Array.from too

    const myArray = undefined
    const entries = myArray?.entries() || [] //assign a default value for your loop