0

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.

3
  • 1
    It doesn’t do anything in that situation. Array.from never returns null or undefined. But if an array is empty, iterating over it doesn’t do anything anyway.
    – Ry-
    Commented Mar 16, 2022 at 3:32
  • @Ry- Appreciate the explanation. So if myArray is empty to begin with, then this part of the code will not crash out - correct?
    – ArthurJ
    Commented Mar 16, 2022 at 3:39
  • 2
    Right. And if it’s already an array, there’s no need to use Array.from either.
    – Ry-
    Commented Mar 16, 2022 at 4:43

1 Answer 1

1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.