DEV Community

Sibusiso Massango
Sibusiso Massango

Posted on

JavaScript Array checks

In JavaScript there are many ways to check the validity of an array, but so far, I haven't found a way which I will be proud of when checking if array has values. Below are ways we use to check whether array has values?

Example:

//Assume you don't know whether the array has values or not, but you want to perform some actions once it does.

let arr = [];

// this should at least tell us whether the array has values or not, but it still assumes that the variable is an array. 

if(arr.length > 0){
}
// What if is not, then below is a full proof example to prevent this.
if(arr && arr.length > 0){
}
// This will check for null and undefined, and then check if it's an array.
Enter fullscreen mode Exit fullscreen mode

The question is there a better way to write the above condition in advance JS?

Top comments (0)