Ankur Ankur - 4 months ago 15
Javascript Question

How do I check if a JavaScript array value is empty or null?

Will this work for testing whether a value at position "index" exists or not, or is there a better way:

// do stuff


All arrays in Javascript contain array.length elements, starting with array[0] up until array[array.length - 1]. By definition, an array element with index i is said to be part of the array if i is between 0 and array.length - 1 inclusive.

That is, arrays in Javascript are linear, starting with zero and going to a maximum, and arrays don't have a mechanism for excluding certain values or ranges from the array. Therefore, 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 (index < array.length) {
  // do stuff

However, it is possible for some array values to be null, undefined, NaN, Infinity, 0, or a whole host of different values. For example, if you add array values by increasing the array.length property, any new values will be undefined. From the question, I suspect you want to know not if a given value is considered part of the array, but whether that value is something meaningful, or has been defined. That is, not "undefined", or perhaps, not "undefined or null".

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


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

It depends on what you're trying to achieve.

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

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