15

I am using like to check if array is not empty

if(array != null){
  //code 
}

I also found like that

if(Array.isArray(array)){
//code
}

and

if(array.length){
//code
}

Which one is better to use above three ?

Mohibul Hasan Rana
  • 237
  • 2
  • 3
  • 16

6 Answers6

27

I suggest to use Array.isArray and the length property of the array

if (Array.isArray(array) && array.length) {
    // code
}

because it checks if array is an array and if the length has a truthy value.


Comparing your attempts:

  1. Truthy check

    if (array != null) { // which is basically the same as if (array) {
        //code 
    }
    

    This is true for all truthy values, like 1, 'a', {}. This result is not wanted.

  2. Array check

    if (Array.isArray(array)) {
        // code
    }
    

    This checks only if array is an array, but not the length of it. Empty arrays returns true, which is not wanted.

  3. Length check

    if (array.length) {
        // code
    }
    

    This works only for objects which may have a property of length, which have a truthy value.

    While this comes close to the wanted result, it might be wrong, for example with objects like

    { length: 'foo' }
    

    or with array-like objects.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
7

If you want to know if an Object is an Array, then Array.isArray() will do.

If you want to know if an Array has items, than array.length !== 0 will do.

If you want to know if a variable is not null than array !== null will do.

philipp
  • 15,947
  • 15
  • 61
  • 106
  • since the length can never be less than 0, you can just write if(array.length) - you don't need to compare against 0 – Andy Apr 21 '21 at 07:41
2

I am use to array.length To check if array is not empty, use if( array.length > 0) {}

gabriel
  • 118
  • 9
2

It's better to check the length of the array but there is one issue in it. Consider if someone entered an undefined value in the array then the array will be empty but still have the length greater than 0.

for(var i=0,i<array.length;i++){
 if(typeof(array[i]) !== 'undefined'){

 };
};
Rap
  • 6,851
  • 3
  • 50
  • 88
Deep Mistry
  • 170
  • 1
  • 1
  • 14
1
var isEmptyArray = function(arr) {
    return (arr || []).length === 0;
}

var arr1 = [1, 2, 3];
var arr2 = [];
var arr3 = undefined;

console.log(isEmptyArray(arr1));  // false
console.log(isEmptyArray(arr2));  // true
console.log(isEmptyArray(arr3));  // true
bugs_cena
  • 495
  • 5
  • 11
1

the best solution is

if (array.length>0){
....
}

but this sentence have a problem if you plan in deleting indexes from the array, since you can have an array like this [undefined,undefined,undefined], whos length is 3 but is technically empty.

var a = [1,2,3];
delete a[0];
delete a[1];
delete a[2];
a.length > 0 /// true
a /// [undefined x 3]

Take this in consideration to make the exact sentence