Languages
[Edit]
EN

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

4 points
Created by:
AnnLen
9220

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

 

Native Advertising
50 000 ad impressions - 449$
ūüöÄ
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

‚̧ԳŹūüíĽ ūüôā

Join