Q:

How to Check If an Array Exists and Not Empty in JavaScript

0

How to Check If an Array Exists and Not Empty in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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:

// 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.");
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get a Random Item from a JavaScript Array... >>
<< How to Check If an Array Exists and Not Empty in J...