EN
TypeScript - check if array is empty or does not exist
0 points
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:
xxxxxxxxxx
1
// for not declared array variable
2
const notExists: boolean = (typeof myArray === 'undefined' || myArray.length == 0);
3
4
// for declared but not defined array variable
5
const notExists: boolean = (myArray == null || myArray.length == 0);
In this section two approaches were presented: when the variable is not defined and when is defined but with null
or undefined
value.
Note: using
typeof
operator we are able to check if variable exists and is defined - this operator checks if varialbe exists.
xxxxxxxxxx
1
const array1: any[] = [];
2
const array2: number[] = [1, 2, 3];
3
//const array3; // not declared and not defined
4
5
console.log(typeof array1 === 'undefined' || array1.length == 0); // true
6
console.log(typeof array2 === 'undefined' || array2.length == 0); // false
7
//console.log(typeof array3 === 'undefined' || array3.length == 0); // false
Output:
xxxxxxxxxx
1
true
2
false
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
xxxxxxxxxx
1
const array1: any[] = [];
2
const array2: number[] = [1, 2, 3];
3
// const array3; // declared but not defined
4
5
console.log(array1 == null || array1.length == 0); // true
6
console.log(array2 == null || array2.length == 0); // false
7
// console.log(array3 == null || array3.length == 0); // false
Output:
xxxxxxxxxx
1
true
2
false