Home > Blockchain >  Is there any downside to checking if the first element of an array exists as a condition, rather tha
Is there any downside to checking if the first element of an array exists as a condition, rather tha

Time:04-05

When ever I have to check if an array has elements in it I always default to checking its length for example...

const array = [];

if (array.length > 0) do something...

However today I thought couldn't I just check if the zero index of the array is not undefined rather than checking the length, I find this saves some typing?

// if the zero index element exists

if (array[0]) do something..

Is there any edge cases or scenarios in which doing this would be bad practice or result in different results than just checking the length of the array?

CodePudding user response:

Even if in most cases the two methods will produce the same result, I strongly recommend using the first one. The only way of telling if an array is empty or not, is by checking its length.

if (array.length) {
  // array is not empty
}

Here are an example where the second method would not work:

const array = [null, "I think", "therefore I am"]

console.log(array.length) // 3
console.log(array[0]) // null, and will evaluate to false

Another case that might occur more often:

const array = [1, 2, 3, 4, 5]

delete array[0]

console.log(array.length) // 5
console.log(array[0]) // undefined, and will evaluate to false

Performance

Interestingly, if the array is empty, it's faster to check if the first element exists:

let array = []

console.time('lengthCheck')
console.log(array.length)
console.timeEnd("lengthCheck")
// about 0.06s in my browser

console.time('itemCheck')
console.log(array[0])
console.timeEnd("itemCheck")
// about 0.025s in my browser

CodePudding user response:

For an empty array, array[0] will throw an index_out_of_bounds exception, whereas array.length will return 0.

  • Related