EN
JavaScript - check if array is empty or does not exist
4
points
In this article, we're going to have a look at how to check if the array is empty or does not exist in JavaScript code.
Quick solution:
// for not declared array variable
var notExists = (typeof myArray === 'undefined' || myArray.length == 0);
// for declared but not defined array variable
var notExists = (myArray == null || myArray.length == 0);
1. Practical example
In this section two approaches were presented: when the variable is not defined and when is defined but with null
or undefined
value.
1.1. If we are not sure the variable is defined.
Note: using
typeof
operator we are able to check if variable exists and is defined - this operator checks if varialbe exists.
// ONLINE-RUNNER:browser;
var array1 = [ ];
var array2 = [1, 2, 3];
//var array3; // not declared and not defined
console.log(typeof array1 === 'undefined' || array1.length == 0); // true
console.log(typeof array2 === 'undefined' || array2.length == 0); // false
console.log(typeof array3 === 'undefined' || array3.length == 0); // false
Output:
true
false
true
1.2. Variable is created but we are not sure if the variable is assigned.
The approach presented in this section is based on the fact the variable is declared. Using variable == null
comparison we are able to test both conditions at the same time: value is null
or undefined
// ONLINE-RUNNER:browser;
var array1 = [ ];
var array2 = [1, 2, 3];
var array3; // declared but not defined
console.log(array1 == null || array1.length == 0); // true
console.log(array2 == null || array2.length == 0); // false
console.log(array3 == null || array3.length == 0); // false
Output:
true
false
true