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 ?
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 ?
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 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.
I am use to array.length
To check if array is not empty, use if( array.length > 0) {}
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'){
};
};
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
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