This is a very common question. And while working on a project, at least one time you will come across the situation where you have to check whether the given JavaScript array is empty or not.
I have seen many times, that developers use array-check to verify if the array is empty or not. This is not the correct way of doing this.
Let’s take an example.
let sample_arr = [] if (sample_arr) { console.log("Array is not empty."); } else { console.log("Array is empty."); }
Output:
Array is not empty.
But this is not the expected output as an array sample_arr
is an empty array. Beware and don’t do this.
This small mistake can lead to real damage and a nightmare situation for your project.
Instead of this, use the length
property of the JavaScript array.
Here is the JavaScript code.
let sample_arr = [] if (sample_arr.length>0) { console.log("Array is not empty."); } else { console.log("Array is empty."); }
Output:
Array is empty.
Basically, the length
property returns the number of elements or items in the array.
As this is simple JavaScript code (Vanilla JS), it will also work with jQuery.
You can also rewrite the above code with the simple inline if-else
statement.
let sample_arr = [] sample_arr.length>0 ? console.log("Array is not empty.") : console.log("Array is empty.");
Output:
Array is empty.
Here if
and else
block is just a one-line code. In this case, it is standard coding practice to use inline if-else
code.
Hope you find this simple and easy tutorial to check if array is empty in jQuery / JavaScript useful for your coding. Keep learning!