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

javascript Check array is empty or not examples

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 does not exist?

First, let’s check whether an array is undefined or not and whether 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 whether a variable is an array or not.

This checks a variable is an array and an array contains 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 if 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.

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
You'll get a notification every time a post gets published here.