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

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

if(arrayName[index]==""){
     // do stuff
}

This question is related to javascript arrays

The answer is


I would recommend creating a function like this:

function isEmptyEl(array, i) {
   return !(array[i]);
}

You could call it like this:

if (isEmptyEl(arrayName, indexVal)) {
   console.log('arrayName[' + indexVal + '] is empty');
}

Forcing the developer to adhere to the isEmptyEl interface will catch input errors such as an undefined arrayName or indexVal variables.

(It's generally good practice to program defensively when programming in Javascript.)

You would get an error thrown like this if arrayName was not defined:

Uncaught ReferenceError: arrayName is not defined
    at <anonymous>:2:15
    at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
    at Object.InjectedScript.evaluate (<anonymous>:694:21)

Similar results for an undefined indexVal.

You get an error if the array or index values do not exist.

For valid input, you'll only get a true if arrayName[indexVal] is any of the following:

  • null
  • undefined
  • NaN
  • empty string
  • 0
  • false

I would like to point out something a few seem to have missed: namely it is possible to have an "empty" array position in the middle of your array. Consider the following:

let arr = [0, 1, 2, 3, 4, 5]

delete arr[3]

console.log(arr)      // [0, 1, 2, empty, 4, 5]

console.log(arr[3])   // undefined

The natural way to check would then be to see whether the array member is undefined, I am unsure if other ways exists

if (arr[index] === undefined) {
  // member does not exist
}

OK, let's first see what would happens if an array value not exist in JavaScript, so if we have an array like below:

const arr = [1, 2, 3, 4, 5];

and now we check if 6 is there at index 5 or not:

arr[5];

and we get undefined...

So that's basically give us the answer, the best way to check if undefined, so something like this:

if("undefined" === typeof arrayName[index]) {
  //array value is not there...
}

It's better NOT doing this in this case:

if(!arrayName[index]) {
  //Don't check like this..
}

Because imagine we have this array:

const arr = [0, 1, 2];

and we do:

if(!arr[0]) {
  //This get passed, because in JavaScript 0 is falsy
}

So as you see, even 0 is there, it doesn't get recognised, there are few other things which can do the same and make you application buggy, so be careful, I list them all down:

  1. undefined: if the value is not defined and it's undefined
  2. null: if it's null, for example if a DOM element not exists...
  3. empty string: ''
  4. 0: number zero
  5. NaN: not a number
  6. false

With Lodash, you can do:

if(_.has(req,'documents')){
      if (req.documents.length)
      _.forEach(req.documents, function(document){
        records.push(document);
      });
} else {
}

if(_.has(req,'documents')) is to check whether our request object has a property named documents and if it has that prop, the next if (req.documents.length) is to validate if it is not an empty array, so the other stuffs like forEach can be proceeded.


try this if array[index] is null

if (array[index] != null) 

I ran into this issue using laravel datatables. I was storing a JSON value called properties in an activity log and wanted to show a button based on this value being empty or not.

Well, datatables was interpreting this as an array if it was empty, and an object if it was not, therefore, the following solution worked for me:

render: function (data, type, full) {
    if (full.properties.length !== 0) {
        // do stuff
    }
}

An object does not have a length property.


Can't we just do this:

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

if(!arrayName[index]){
     // do stuff
}

if(typeof arr ==='object' && arr instanceof Array ){
   if(!arr.length){
      println 'empty'
   }else{
      printn 'not Empty'
   }

}else{
   println 'Null'
}

If you mean by 'Null' -> Its elements are null or equals to '' , in this case : Check if the array is empty after filtering all 'null' elements

if(!arr.clean().length){return 'is null'}

Of course ,Add Clean method before :

Array.prototype.clean=function(){return this.filter(function(e){return (typeof  e !=='undefined')&&(e!= null)&&(e!='')})}

To check if it has never been defined or if it was deleted:

if(typeof arrayName[index]==="undefined"){
     //the index is not in the array
}

also works with associative arrays and arrays where you deleted some index

To check if it was never been defined, was deleted OR is a null or logical empty value (NaN, empty string, false):

if(typeof arrayName[index]==="undefined"||arrayName[index]){
     //the index is not defined or the value an empty value
}

Short and universal approach

If you want to check any array if it has falsy values (like false, undefined, null or empty strings) you can just use every() method like this:

array.every(function(element) {return !!element;}); // returns true or false

For example:

['23', null, 2, {key: 'value'}].every(function(element) {return !!element;}); // returns false

['23', '', 2, {key: 'value'}].every(function(element) {return !!element;}); // returns false

['23', true, 2, {key: 'value'}].every(function(element) {return !!element;}); // returns true

If you need to get a first index of falsy value, you can do it like this:

let falsyIndex; 

if(!['23', true, 2, null, {key: 'value'}].every(function(element, index) {falsyIndex = index; return !!element;})) {
  console.log(falsyIndex);
} // logs 3

If you just need to check a falsy value of an array for a given index you can just do it like this:

if (!!array[index]) {
  // array[index] is a correct value
}
else {
  // array[index] is a falsy value
}

Real detection: in operator

This question age is about 10 years and it is surprising that nobody mention about this yet - however some people see the problem when we use delete operator (e.g here). This is also a little bit counter intuitive solution but the in operator which works in 'object world' can also work with arrays (because we can look on array indexes like on 'keys'...). In this way we can detect and distinct between undefined array value and value (index) removed by delete

if(index in arrayName) {
   // do stuff 
}

_x000D_
_x000D_
let arr = [0, 1, 2, 3, null, undefined,6]

delete arr[2]; // we delete element at index=2

if(2 in arr) console.log('You will not see this because idx 2 was deleted');
if(5 in arr) console.log('This is element arr[5]:', arr[5]);



// Whole array and indexes bigger than arr.length:
for(let i=0; i<=9; i++) {
  let val = (i in arr) ? arr[i] : 'empty'
  let bound = i<arr.length ? '' : '(out of range)'
  console.log(`${i} value: `, val, bound);
}


console.log('Look on below aray on chrome console (not in SO snippet console)');
console.log('typeof arr:', typeof arr);
console.log(arr);
_x000D_
_x000D_
_x000D_

Chrome console reveals some info about snippet array with deleted index 2 - this index actually not exists at all (!!!) (same way as key is removed from object). What is also interesting here array is viewd as key-value pairs (we even see 'length' key). It is also interesting that typeof arr is Object (!!!), the delete and in operator works like for JS objects (also square brackets notation arr[idx] and obj[key] is similar) - so it looks like array is some special JS object in the core.

enter image description here

To get similar effect without delete define array as follows

[0, 1,, 3, null, undefined, 6] // pay attention to double comma: ",,"

You can use Loadsh library to do this more efficiently, like:

if you have an array named "pets", for example:

var pets = ['dog', undefined, 'cat', null];

console.log(_.isEmpty(pets[1])); // true
console.log(_.isEmpty(pets[3])); // true
console.log(_.isEmpty(pets[4])); // false

_.map( pets, (pet, index) => { console.log(index + ': ' + _.isEmpty(pet) ) });

To check all array values for null or undefined values:

_x000D_
_x000D_
var pets = ['dog', undefined, 'cat', null];_x000D_
_x000D_
console.log(_.isEmpty(pets[1])); // true_x000D_
console.log(_.isEmpty(pets[3])); // true_x000D_
console.log(_.isEmpty(pets[4])); // false_x000D_
_x000D_
_.map( pets, (pet, index) => { console.log(index + ': ' + _.isEmpty(pet) ) });
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

Check more examples in http://underscorejs.org/


if(arrayName.length > index && arrayName[index] !== null) {
    //arrayName[index] has a value
}

It depends on what you mean with "empty".

When you attempt to get the value of a property on an object which has no property with that name, you will get the value undefined.

That's what happens with sparse arrays: not all indices between 0 and array.length-1 exist.

So you could check if array[index] === undefined.

However, the property index could exist with an undefined value. If you want to filter out this case, you can use the in operator or hasOwnProperty, as described in How do I check if an object has a property in JavaScript?

index in array;
array.hasOwnProperty(index);

If you want consider an existing property with an undefined or null value to not exist, you can use the loose comparison array[index] == undefined or array[index] == null.

If you know the array is not sparse, you could compare index with array.length. But to be safe, you may want to ensure that index really is an array index, see Check if property name is array index


I think this decision is appropriate for guys who prefer the declarative functional programming over the imperative OOP or the procedural. If your question is "Is there some values inside? (a truthy or a falsy value)" you can use .some method to validate the values inside.

[].some(el => el || !el);
  • It isn't perfect but it doesn't require to apply any extra function containing the same logic, like function isEmpty(arr) { ... }.
  • It still sounds better than "Is it zero length?" when we do this [].length resulting to 0 which is dangerous in some cases.
  • Or even this [].length > 0 saying "Is its length greater than zero?"

Advanced examples:

[    ].some(el => el || !el); // false
[null].some(el => el || !el); // true
[1, 3].some(el => el || !el); // true

when you create empty array values ARE NOT undefined, they are EMPTY

var arr = new Array(10); // (10) [empty × 10]

but when you get item by index receive undefined

arr[0]; // undefined

so you can't know by === comparing if they are undefined or empty

we can make it by using JSON.stringify, converting whole array it replaces empty values with null

JSON.stringify(arr); // "[null,null,null,null,null,null,null,null,null,null]"
JSON.stringify(arr[0]); // but for single item it returns undefined

so real check for empty value:

arr[0] !== null && JSON.stringify(arr.map(item => !item)).slice(1, -1).split(',')[0] === 'null'
  1. compare item with null (should be not equal)
  2. map array removing false instead existing values (ensure stringified structure to be comma-separated without redundant commas)
  3. JSON.stringify array
  4. remove brackets from string
  5. split into array by comma
  6. compare with null

Using only .length is not safe and will cause an error in some browsers. Here is a better solution:

if(array && array.length){   
   // not empty 
} else {
   // empty
}

or, we can use:

Object.keys(__array__).length