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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago