How to Check if an Array is Null or Empty in TypeScript?

As a TypeScript developer, you should always ensure that your arrays are properly checked for null or empty values, which can prevent numerous bugs and runtime errors. In this tutorial, I will explain how to check if an array is null or empty in TypeScript using various methods with examples.

Check if an Array is Null or Empty in TypeScript

TypeScript, being a superset of JavaScript, inherits all array functionalities from JavaScript. The best way to check if an array is empty is by using the .length property. However, additional checks are required to ensure the array is not null or undefined.

Checking if an Array is Null or Undefined

Before checking if an array is empty, it’s crucial to ensure that the array is neither null nor undefined in TypeScript. This can be done using a simple conditional check, here is the complete code:

let cities: string[] | null | undefined;

// Example array
cities = null;

if (cities === null || cities === undefined) {
    console.log("The array is null or undefined.");
} else {
    console.log("The array is not null or undefined.");
}

In this example, the cities array is initially set to null. The conditional check verifies if cities is null or undefined, and logs an appropriate message.

Here is the exact output in the screenshot below:

Check if an Array is Null or Empty in TypeScript

Check out Remove Empty Strings from an Array in TypeScript

Checking if an Array is Empty

Once you’ve confirmed that the array is not null or undefined, you can proceed to check if it is empty using the .length property. Here is the TypeScript code you can use.

let cities: string[] = [];

// Example array
cities = [];

if (cities.length === 0) {
    console.log("The array is empty.");
} else {
    console.log("The array is not empty.");
}

Here, the cities array is empty, and the .length property returns 0, indicating that the array is indeed empty.

Check out Check if an Array is Not Empty in TypeScript

Combine Null, Undefined, and Empty Checks

To handle all cases in a single conditional statement, you can combine the checks. Here is the complete code to check null, undefined and empty checks in TypeScript.

let cities: string[] | null | undefined;

// Example array
cities = [];

if (!cities || cities.length === 0) {
    console.log("The array is null, undefined, or empty.");
} else {
    console.log("The array is not null, undefined, or empty.");
}

This combined check ensures that the array is neither null nor undefined and also verifies if it is empty.

Here is the exact output in the screenshot below:

How to Check if an Array is Null or Empty in TypeScript

Check out Check if an Array is Empty in TypeScript

Practical Examples

Let me show you some practical examples.

Example 1: Checking a List of US Cities

Suppose you have an application that processes a list of US cities. You need to ensure that the list is valid before performing operations on it.

let usCities: string[] | null | undefined;

// Example array
usCities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"];

if (!usCities || usCities.length === 0) {
    console.log("The list of US cities is null, undefined, or empty.");
} else {
    console.log("Processing the list of US cities...");
    // Perform operations on the array
    usCities.forEach(city => console.log(city));
}

In this example, the usCities array is populated with a list of major US cities. The combined check ensures that the array is valid before iterating over it.

Example 2: Validating User Input for State Names

Consider an application where users input the names of US states. The input needs to be validated to ensure it is not null, undefined, or empty.

function validateStateInput(states: string[] | null | undefined): void {
    if (!states || states.length === 0) {
        console.log("No states provided.");
    } else {
        console.log("Validating state names...");
        // Perform validation on the array
        states.forEach(state => {
            if (state.length < 2) {
                console.log(`Invalid state name: ${state}`);
            } else {
                console.log(`Valid state name: ${state}`);
            }
        });
    }
}

// Example usage
validateStateInput(["California", "Texas", ""]);

In this example, the validateStateInput function checks the input array of state names. It ensures the array is valid and then performs additional validation on each state name.

Read Declare and Initialize Empty Arrays in TypeScript

Advanced Techniques to Check if an Array is Null or Empty

While the basic checks are sufficient for most use cases, there are advanced techniques that can further enhance your array validation logic.

Using TypeScript Utility Types

TypeScript provides utility types that can help in refining your checks. For instance, you can use the NonNullable type to ensure that the array is not null or undefined:

type NonNullableArray<T> = NonNullable<T[]>;

let states: NonNullableArray<string> | undefined;

// Example array
states = ["California", "Texas", "Florida"];

if (!states || states.length === 0) {
    console.log("The array is null, undefined, or empty.");
} else {
    console.log("The array is not null, undefined, or empty.");
}

Creating a Custom Type Guard

A custom type guard can provide a more robust solution for array checks in TypeScript. This approach leverages TypeScript’s type system to ensure type safety. Here is an example.

function isNonEmptyArray<T>(arr: T[] | null | undefined): arr is T[] {
    return !!arr && arr.length > 0;
}

let cities: string[] | null | undefined;

// Example array
cities = ["San Francisco", "Boston", "Seattle"];

if (isNonEmptyArray(cities)) {
    console.log("The array is not null, undefined, or empty.");
    // Perform operations on the array
    cities.forEach(city => console.log(city));
} else {
    console.log("The array is null, undefined, or empty.");
}

In this example, the isNonEmptyArray function acts as a type guard, ensuring that the array is valid before proceeding with operations.

Conclusion

In this tutorial, I have explained various methods to check if an array is null or empty in TypeScript. We started with basic checks using conditional statements and the .length property, and then moved on to more advanced techniques using TypeScript utility types and custom type guards.

You may also like: