How to check if an array is empty in JavaScript?

[2622 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 }
                 






Comments










Search Anything:

Sponsored Deals ends in





Technical Quizzes Specially For You:

Search Tags

    javascript empty variable check

    check if variable is empty in java