542

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
}
2
  • 6
    Please note, not wanting to check if the whole array is empty, just a certain location which has the index value of "index"
    – Ankur
    Commented Apr 20, 2010 at 3:42
  • The title can be improved by saying "How do I check in JavaScript if a value exists at a certain array index".
    – demisx
    Commented Sep 26, 2017 at 15:37

19 Answers 19

766

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
}  
14
  • 6
    It's highly likely that the OP knows what sort of array s/he's dealing with, but just for completeness: array-like objects also typically contain a length property, in which case the later two examples are more appropriate. Commented Apr 20, 2010 at 3:58
  • 10
    you can always replace foo !== 'undefined' && foo !== null with just foo != null
    – thinklinux
    Commented Dec 7, 2012 at 16:43
  • 1
    @TheComposer according to the language the size of an array in Javascript is defined by array.length, and the array is said to comprise all elements from 0 to array.length - 1. Not all of these values will be defined values though. If you use the delete keyword on an array member it will set that member back to being undefined, just like if you extend an array by incrementing its array.length parameter, the new values will start as undefined. In reality, Javascript implementations will probably optimise array storage and some or all undefined values may occupy no memory. Commented Feb 27, 2014 at 0:58
  • 1
    array.length does not iterate over anything, it's just a single number. Commented Jun 26, 2017 at 0:13
  • 2
    This answer doesn't cover cases where an array index is not set. new Array(1)[0] === undefined but the value is empty. [undefined][0] === undefined but the value is set; the array has a value. The only perfect answer is using in or hasOwnProperty()--idx in array or array.hasOwnProperty(idx)--per this answer: stackoverflow.com/a/39171620/3120446
    – dx_over_dt
    Commented Jul 9, 2019 at 20:19
352

Can't we just do this:

if(arrayName.length > 0){   
    //or **if(arrayName.length)**
    //this array is not empty 
}else{
   //this array is empty
}
11
  • 11
    The question was about how to test if a particular index of an array exists or not. Commented Apr 9, 2014 at 1:10
  • 27
    Would if(arrayName.length) {... make any difference?
    – siannone
    Commented Oct 23, 2015 at 12:08
  • 14
    Why so many upvotes? This clearly does not answer the question.
    – algiogia
    Commented Aug 31, 2016 at 13:02
  • 10
    if(arrayName.length) {... fails on null Commented Dec 30, 2016 at 5:00
  • 5
    this fails with [undefined, undefined] which is an array with length = 2. Commented Apr 5, 2017 at 11:29
45

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
3
  • 2
    «Please note, not wanting to check if the whole array is empty, just a certain location which has the index value of "index"»
    – Oriol
    Commented Aug 26, 2016 at 16:44
  • nice, short and simple answer for those who want to check the whole array Commented Jan 31, 2018 at 13:57
  • This answer completely misses OP question, the question is to find if an array Index is empty or not, not the whole array!
    – spacing
    Commented Aug 8, 2020 at 18:13
26
if(!arrayName[index]){
     // do stuff
}
3
  • 9
    This would also do stuff if the array value exists but is 0, null, "", etc. Commented Apr 20, 2010 at 3:51
  • Thomas is right; however, this is sufficient for many cases (which you should probably enumerate). Commented Apr 20, 2010 at 3:56
  • by far the simplest way Commented Mar 14, 2020 at 8:08
9
if(arrayName.length > index && arrayName[index] !== null) {
    //arrayName[index] has a value
}
6
  • @thomasrutter I'm having trouble coming up with a way it would be possible to end up with an array element that is undefined.
    – Rex M
    Commented Apr 20, 2010 at 4:34
  • Hmmm, does (myarray[1] = undefinedvariable) work? Or just (myarray[1] = undefined)? Commented Apr 20, 2010 at 4:47
  • @thomasrutter both of those would throw an exception, no? (undefinedvariable is undefined)
    – Rex M
    Commented Apr 27, 2010 at 21:42
  • 2
    You can test it for yourself using something like Firebug. In Javascript, reading the value of an undefined variable does not throw an exception - it returns the undefined value. Commented Apr 28, 2010 at 1:43
  • @thomasrutter you're wrong in your first comment. x == null will only ever be true for null or undefined, nothing else. Likewise, x != null will be true for anything that is neither null or undefined. Unless you specifically need to look for undefined, just lean in to the implicit conversion goodness. Commented Oct 23, 2013 at 1:04
8

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
}
7
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!='')})}
7

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

2
  • 2
    This is the only answer which properly distingushes between unset array items (which don't have any value) and items which are set to the undefined value. The 2 states are blurred by the fact that accessing an unset array item returns undefined, but they are different.
    – olivr
    Commented Oct 6, 2016 at 4:49
  • Use hasOwnProperty when you have an array with potentially unset values (different from undefined or null). Commented Jan 15, 2018 at 13:15
5

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
2

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
}
2

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 
}

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);

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: ",,"
1

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
0

try this if array[index] is null

if (array[index] != null) 
0

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.

0

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
}
0

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.

0

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
0

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
-1

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:

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) ) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

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

1
  • fn(){} is a syntax error, and it's not clear at all how this helps checking whether an array item exists at a certain index or not.
    – Oriol
    Commented Aug 26, 2016 at 16:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.