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

JavascriptArrays

Javascript Problem Overview


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
}

Javascript Solutions


Solution 1 - Javascript

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

Can't we just do this:

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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
}

Solution 7 - Javascript

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 https://stackoverflow.com/q/135448/1529630

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 https://stackoverflow.com/q/38163612/1529630

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Solution 10 - Javascript

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
}

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

try this if array[index] is null

if (array[index] != null) 

Solution 14 - Javascript

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.

Solution 15 - Javascript

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
}

Solution 16 - Javascript

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.

Solution 17 - Javascript

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

Solution 18 - Javascript

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

Solution 19 - Javascript

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/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnkurView Question on Stackoverflow
Solution 1 - JavascriptthomasrutterView Answer on Stackoverflow
Solution 2 - JavascriptmadiView Answer on Stackoverflow
Solution 3 - JavascriptJoniView Answer on Stackoverflow
Solution 4 - Javascriptx2.View Answer on Stackoverflow
Solution 5 - JavascriptRex MView Answer on Stackoverflow
Solution 6 - JavascriptindreedView Answer on Stackoverflow
Solution 7 - JavascriptOriolView Answer on Stackoverflow
Solution 8 - JavascriptAbdennour TOUMIView Answer on Stackoverflow
Solution 9 - Javascriptl3xView Answer on Stackoverflow
Solution 10 - JavascriptBenoit RanqueView Answer on Stackoverflow
Solution 11 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 12 - JavascriptAlirezaView Answer on Stackoverflow
Solution 13 - JavascriptKishanView Answer on Stackoverflow
Solution 14 - JavascriptPristine KallioView Answer on Stackoverflow
Solution 15 - JavascriptLuca C.View Answer on Stackoverflow
Solution 16 - Javascriptkjdion84View Answer on Stackoverflow
Solution 17 - JavascriptPurkhalo AlexView Answer on Stackoverflow
Solution 18 - JavascriptMatvii StelmakhView Answer on Stackoverflow
Solution 19 - JavascriptalvaropacoView Answer on Stackoverflow