Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❀ đŸ’»

If you think sharing knowledge and helping other is valuable.

join our community - Click here

JavaScript - how to check if array is empty or does not exist?

0 contributions
4 points

In this article, we're going to have a look at how to check if array is empty or does not exist in JavaScript code.

Simple overview:

// 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 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

1.2. Variable is created but we are not sure if variable is assigned.

Approach presented in this section is based on fact the variable is declared. Using variable == null comparision we are able to test both conditions in 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


0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more