How to check if an array is empty in JavaScript?

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 }

Need Programming or any Technical Related Books, Courses or Help Chat with us


Today's Recommended Deals

Online Games
Play 2048 Game Online and Relax.
Play 2048 Game Online

Search Tags

    javascript empty variable check

    check if variable is empty in java