How to Check If an Array Exists and Not Empty in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Use the typeof
Operator in combination with isArray()
Method and length
Property
You can simply use the JavaScript typeof
operator in combination with the isArray()
method and the length
property to check if an array exist as well as if it is non-empty.
In the following example the variable myVar
will pass the test if and only if it is defined and it is an array with at least one element. Experiment with the variable value and see how it works:
Example
Try this code »// Sample variable
var myVar = [1, 2, 3];
// Testing variable
if(typeof myVar != 'undefined' && Array.isArray(myVar) && myVar.length > 0) {
console.log("The array exists and it is not empty.");
} else {
console.log("The variable failed the test.");
}
Related FAQ
Here are some more FAQ related to this topic: