Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best procedure to check an array is empty or not in jQuery? [duplicate]

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 ?

like image 879
Mohibul Hasan Rana Avatar asked May 31 '17 06:05

Mohibul Hasan Rana


People also ask

How do you check the array is empty or not in jQuery?

We can use jQuery's isEmptyObject() method to check whether the array is empty or contains elements. The isEmptyObject() method accepts a single parameter of type Object, which is the object to be checked and returns a boolean value true if the object is empty and false if not empty.

How do you check the array is empty or not?

The array can be checked if it is empty by using the array. length property. This property returns the number of elements in the array. If the number is greater than 0, it evaluates to true.

How do you check if an array of objects is empty in JavaScript?

Use the Object. entries() function. It returns an array containing the object's enumerable properties. If it returns an empty array, it means the object does not have any enumerable property, which in turn means it is empty.

Is empty array falsey?

Values not on the list of falsy values in JavaScript are called truthy values and include the empty array [] or the empty object {} . This means almost everything evaluates to true in JavaScript — any object and almost all primitive values, everything but the falsy values.


1 Answers

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.

like image 90
Nina Scholz Avatar answered Oct 06 '22 13:10

Nina Scholz