Categories: Development

Checking if an array is empty or not with Javascript

Checking if an array is empty or not with Javascript.

 

let the_array = [];

Check if the array is empty

Array.isArray() checks if the value passed in is an array and not a string, bool etc.

This only returns true when the value passed in is a valid array.

array.length will return false because 0 isn’t a “true” value.

if (!Array.isArray(the_array) || !the_array.length) {
   //This condition is met
}

Now filling the array:

the_array.push('Orange');
the_array.push('Kiwi');
the_array.push('Lemon');

Check if the array is not empty

Doing the reverse of the first empty check can be done. However, you want to check for a valid array and that it has a length greater than 0.

if (Array.isArray(the_array) && the_array.length > 0) {
   //This condition is met
}

Whilst a condition for the_array.length to be true can be used, setting the condition as the_array.length > 0 is more specific and doesn’t rely on the conversion of a number as being true.

CodePen example:

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago