Check the array has empty element or not

First, note the difference between empty slots and slots with undefined value:

var arr = [/*empty slot*/, undefined];
Object.keys(arr); // ["1"] but not "0"
"0" in arr; // false
"1" in arr; // true

ES5 array methods skip empty slots. ES6 [].includes does not.

That means you can use

arr.includes(undefined); // has empty slot OR contains undefined value
arr.indexOf(undefined) > -1; // contains undefined value

If you want to test only if there are empty slots, you can iterate manually with a for loop and check whether all indices between 0 and the length of the array are present, e.g. with in operator.

(function() {
  for(var i=0; i<arr.length; ++i) if(!(i in arr)) return true;
  return false;
})(); // has empty slot

Or you can also use ES5 array methods and check if they skipped an index.

var n = 0;
arr.some((_,i) => i !== n++); // has empty slot

As of ES2016, you should use Array.prototype.includes:

const array = ["a", "b", , "d"];
array.includes(undefined); // true

(You don't need to write undefined, but this makes it more clear what's happening.)

Note that this method treats slots valued undefined and empty slots the same, although they're not. If you need to differentiate these two cases as well, starting from ES2017, you can use Object.values making the following expression true if there are empty slots in the array:

Object.values(array).length !== array.length; // true

You could also use Array.prototype.findIndex()

var arr = ['a', 'b', , 'd'];

document.write(arr.findIndex(e => e === undefined) > -1);

Tags:

Javascript