How do I check in JavaScript if a value exists at a certain array index?

Solution 1:

Conceptually, arrays in JavaScript contain array.length elements, starting with array[0] up until array[array.length - 1]. An array element with index i is defined to be part of the array if i is between 0 and array.length - 1 inclusive. If i is not in this range it's not in the array.

So by concept, arrays are linear, starting with zero and going to a maximum, without any mechanism for having "gaps" inside that range where no entries exist. To find out if a value exists at a given position index (where index is 0 or a positive integer), you literally just use

if (i >= 0 && i < array.length) {
  // it is in array
}

Now, under the hood, JavaScript engines almost certainly won't allocate array space linearly and contiguously like this, as it wouldn't make much sense in a dynamic language and it would be inefficient for certain code. They're probably hash tables or some hybrid mixture of strategies, and undefined ranges of the array probably aren't allocated their own memory. Nonetheless, JavaScript the language wants to present arrays of array.length n as having n members and they are named 0 to n - 1, and anything in this range is part of the array.

What you probably want, however, is to know if a value in an array is actually something defined - that is, it's not undefined. Maybe you even want to know if it's defined and not null. It's possible to add members to an array without ever setting their value: for example, if you add array values by increasing the array.length property, any new values will be undefined.

To determine if a given value is something meaningful, or has been defined. That is, not undefined, or null:

if (typeof array[index] !== 'undefined') {

or

if (typeof array[index] !== 'undefined' && array[index] !== null) {

Interestingly, because of JavaScript's comparison rules, my last example can be optimised down to this:

if (array[index] != null) {
  // The == and != operators consider null equal to only null or undefined
}  

Solution 2:

Can't we just do this:

if(arrayName.length > 0){   
    //or **if(arrayName.length)**
    //this array is not empty 
}else{
   //this array is empty
}