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.");
}
Use the
typeofOperator in combination withisArray()Method andlengthPropertyYou can simply use the JavaScript
typeofoperator in combination with theisArray()method and thelengthproperty to check if an array exist as well as if it is non-empty.In the following example the variable
need an explanation for this answer? contact us directly to get an explanation for this answermyVarwill 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: