Clue Mediator

How to check if an array is empty or exist in JavaScript

📅February 9, 2022

If you are using arrays in your project and would like to use the array method, we suggest you check if the array is empty or exists. So here we will show you the possible ways to verify the Array in JavaScript.

Checkout more articles on JavaScript

To check if an array exists and length is greater than zero

We will recommend you to use the Array.isArray() and length property to verify an array.

var myArr = [ 1, 2, 3 ];
if (Array.isArray(myArr) && myArr.length) {
    // Array exists and Length is greater than 0
}

Let's also look at the following attempts.

1. Truthy check

if (myArr != null) { // which is basically the same as if (myArr) {
    // code
}

This is true for all truthy values, like `1`, `'a'`, `{ }`. This result is not wanted.

2. Array check

if (Array.isArray(myArr)) {
    // code
}

This checks only if `myArr` is an array, but not the length of it. Empty arrays return `true`, which is not wanted.

3. Length check

if (myArr.length) {
    // code
}

This works only for objects that may have a property of length, which have a truthy value.

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂