{

How to check if the array is empty or does not exist in javascript?


It is a short tutorial on how to check 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 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 an array is null or does not exist?

First, let’s check an array is undefined or not and the length is zero or not using the below if conditional expression.

let myarray=[]
if (myarray === undefined || myarray.length == 0) {
}

It checks for the array is undefined or empty. But does not check for null

It does not check whether the array is declared or not.

Array isArray method checks a variable is an array or not.

This checks an variable is an array and array contain values.

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, checks given variable is undefined or not Need to check a variable is an array.

use instanceOf operator to check variable is an array or not

if (typeof myarray=="undefined" || !(myarray instanceof Array)) {
    var myarray = [];
}

It creates a new array if the array does not exist.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.