Languages
[Edit]
EN

TypeScript - check if array is empty or does not exist

0 points
Created by:
Paluskitten
356

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

Quick solution:

// for not declared array variable
const notExists: boolean = (typeof myArray === 'undefined' || myArray.length == 0);

// for declared but not defined array variable
const notExists: boolean = (myArray == null || myArray.length == 0);

 

1. Practical example

In this section two approaches were presented: when the 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.

const array1: any[] = [];
const array2: number[] = [1, 2, 3];
//const 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

Output:

true
false

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

The approach presented in this section is based on the fact the variables were declared. Using variable == null comparison we are able to test both conditions at the same time: value is null or undefined

const array1: any[] = [];
const array2: number[] = [1, 2, 3];
// const 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

Output:

true
false
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join