How to check if the array is empty or does not exist in JavaScript?
- Admin
- Mar 10, 2024
- Javascript
It is a short tutorial on how to check whether an array is empty or null or does not exist.
An array is a group of elements stored under a single name.
Let’s see how we can check if an array is undefined
, null
, and length
is zero.
An array is empty if the length of an array is zero. An array object exists if it is not undefined
or null
.
How to check if an array is null or undefined or length is zero?
To check whether an array is null or not, You can compare the array variable with a null value using the ===
operator.
let myarray = null;
if (myarray === null) {
console.log("array is null")
}
Next, let’s check whether an array is undefined
or not,
Compare variable with undefined
value using triple equal operator(===
)
if (myarray === undefined) {
console.log("array is not defined")
}
To check array length is zero or not, use the length
property on the array, which returns zero if the array is empty. So compare the result with zero using if conditional statements.
let myarray = [];
if (myarray.length == 0) {
}
It checks if the array is undefined or empty. But does not check for null.
It does not check whether the array is declared or not.
The array isArray
method checks whether a variable is an array or not.
> const a=[]
undefined
> Array.isArray(a)
true
> const b=12
undefined
> Array.isArray(b)
false
It returns true, if a variable is an array, else return false.
Below checks a variable is an array, checks if the array contains a value, not empty.
if (Array.isArray(myarray) || myarray.length) {
}
Sometimes you want to create an array if it does not exist.
How to create an array if an array does not exist yet?
First, check given variable is undefined
or not. Need to check if a variable is an array.
use the instanceOf
operator to check variable is an array or not. It returns true if a variable is an Array type, else returns false for other types.
> const a=[]
undefined
> const b=12
undefined
> a instanceof Array
true
> b instanceof Array
false
if (typeof myarray == "undefined" || !(myarray instanceof Array)) {
var myarray = [];
}
It creates a new array if the array does not exist.