JavaScript Fundamentals: Learning the Language of the Web
How to Quickly Check If an Array is empty or not in Javascript?
Introduction
In this article, we will see how to check an array if it's empty or not with array methods and detailed examples.
Approach: Using Array.isArray() method and array.length property
The Array.isArray() method can be used to determine whether an array is actually there and whether it exists. If the Object supplied as a parameter is an array, this function returns true. Additionally, it determines whether the array is undefined or null.
The array.length property can be used to determine whether the array is empty. The array's element count is returned by this attribute. The integer evaluates to true if it is bigger than 0.
When used with the AND(&&) operator, this method and property can be used to check whether the array is present and not empty.
Syntax
Example
Output
Here, we can see that charArr is an array and so meets the second requirement to determine whether the length of the array is empty. The function returns False since the array is not empty because it contains three elements. Since it is an array once more in the second scenario, arrTwo, it meets the second requirement. The function in this case returns True because the array is empty.
Example 2
Output
Note
The function Array.isArray() returns TRUE since Array.prototype is an array in and of itself.
Example 3
Output
Example 4
Output
Conclusion
In this article, we understood the methods to check if an array is empty or not.