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
2
  • 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 Commented Dec 14, 2019 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 Commented Dec 15, 2019 at 15:16

1 Answer 1

1

You can use hasOwnProperty:

const arr = [true,undefined,,true];
console.log('undefined', arr.hasOwnProperty('1'));
console.log('hole', arr.hasOwnProperty('2'));

Sign up to request clarification or add additional context in comments.

1 Comment

hm... there seems to be a 4th methd: a.propertyIsEnumerable(1) // false, b.propertyIsEnumerable(1) // true

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.