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
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!
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
Array.from
never returns null or undefined. But if an array is empty, iterating over it doesn’t do anything anyway.myArray
is empty to begin with, then this part of the code will not crash out - correct?Array.from
either.