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: