How to check if an array is empty in JavaScript?

(279 Views)


Sometimes while writing a javascript code, we need to validate whether an array is empty or not to prevent js code from given irrelevant output. In this article, I have mentioned some ways to verify if array is empty in Javascript

Validate if an array is empty in JavaScript
if (array && array.constructor === Array && array.length === 0) { // strictly an empty array } else { // either null, or not an array or not an empty array }

In the above code, array.constructor checks if the object is an Array.

Another Method

if(Array.isArray(yourVariable) && yourVariable.length === 0) // empty array } else { // not empty }

Solution Worked 0 UpvotesUpvote

        

Solution Didn't Worked 0 DownvotesDownvote



Comments



Search


Search Tags