1

What are all the methods that can do that?

I only know of two methods. To summarize, to find whether arr[1] is empty or undefined, use

1 in arr

or

Object.keys(arr).includes("1")

but the second method may possibly create a big array to begin with.

// running inside of Node 6.11.0

// Methods that works:
> a = Array(3)
[ , ,  ]

> b = Array.from({length:3})
[ undefined, undefined, undefined ]

> 1 in a
false
> 1 in b
true

> Object.keys(a).includes("1")
false
> Object.keys(b).includes("1")
true

// Method that doesn't
> a[1]
undefined
> b[1]
undefined

> a[1] === undefined
true
> b[1] === undefined
true
nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • that post suggested "the only way is to check its key"... Is that actually the case and I suppose the 3 ways we know `1 in arr`, `Object.keys(arr).includes("1")` and `arr.hasOwnProperty("1")` are all checking its key – nonopolarity Dec 14 '19 at 23:27
  • That's because that's literally the difference. There is nothing special about arrays here. It's the same to check if a object does not has a key or has a key with undefined as value – Lux Dec 15 '19 at 15:16

1 Answers1

1

You can use hasOwnProperty:

const arr = [true,undefined,,true];
console.log('undefined', arr.hasOwnProperty('1'));
console.log('hole', arr.hasOwnProperty('2'));
Lux
  • 17,835
  • 5
  • 43
  • 73