JavaScript Array checks

samassango

Sibusiso Massango

Posted on February 23, 2024

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?

💖 💪 🙅 🚩
samassango
Sibusiso Massango

Posted on February 23, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JavaScript Array checks
javascript JavaScript Array checks

February 23, 2024

Queuing Rest Apis using JavaScript
javascript Queuing Rest Apis using JavaScript

April 10, 2023

What is the first thing everyone do?
javascript What is the first thing everyone do?

July 24, 2022

#9 Guess the output ???
javascript #9 Guess the output ???

March 24, 2022