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 ?
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.
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.
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.
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.
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:
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With