How to Check if an Array is Empty in TypeScript?

While working with TypeScript programming, you will get requirements to check if a TypeScript array is empty. In this tutorial, I will explain various ways to check if an array is empty in TypeScript with detailed examples. Let me show you all the methods with examples.

Here are various methods to check if an array is empty in TypeScript.

1. Using the .length Property

The best way to check if an array is empty in TypeScript is by using the length property. If the length is 0, the array is empty. Here’s an example:

const employees: string[] = [];

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

In this code snippet, we declare an empty array called employees. We then use an if statement to check if the length of the array is strictly equal to 0. If it is, we log the message “The employee array is empty.” Otherwise, we log “The employee array is not empty.”

Here is the exact output in the screenshot below:

Check if an Array is Empty in TypeScript

Check out Declare and Initialize Empty Arrays in TypeScript

2. Combine Array.isArray() with .length

When working with arrays in TypeScript, it’s important to ensure that the variable you’re checking is actually an array. You can use the Array.isArray() method in combination with the length property for a more robust check. Here’s an example:

function processData(data: any) {
  if (Array.isArray(data) && data.length === 0) {
    console.log("The data is an empty array.");
  } else {
    console.log("The data is not an empty array.");
  }
}

const customers: string[] = [];
processData(customers);

In this example, we define a function called processData that takes a parameter data of type any. Inside the function, we first use Array.isArray(data) to check if data is an array. If it is an array and its length is 0, we log the message “The data is an empty array.” Otherwise, we log “The data is not an empty array.”

We then call the processData function with an empty array called customers. This approach ensures that we’re dealing with an actual array before checking its emptiness.

Here is the exact output in the screenshot below:

Typescript Check if an Array is Empty

Check out Create and Use an Empty String Array in TypeScript

3. Guarding Against Empty Arrays in TypeScript

TypeScript provides type guards that allow you to narrow down the type of a variable within a conditional block. You can leverage this feature to guard against empty arrays. Here’s an example:

function getFirstOrder(orders: string[]): string {
  if (orders.length === 0) {
    throw new Error("No orders found.");
  }
  return orders[0];
}

const recentOrders: string[] = ["ORD-1234", "ORD-5678"];
const firstOrder = getFirstOrder(recentOrders);
console.log(firstOrder);

In this code snippet, we have a function called getFirstOrder that takes an array of orders as a parameter. Inside the function, we check if the length of the orders array is 0. If it is, we throw an error with the message “No orders found.” This acts as a guard to prevent further execution if the array is empty.

If the orders array is not empty, we return the first element using orders[0]. We then call the getFirstOrder function with an array called recentOrders and store the result in the firstOrder variable. Finally, we log the firstOrder to the console.

By throwing an error when the array is empty, we ensure that our code handles empty arrays gracefully and prevents potential runtime errors.

Check out How to Iterate Over Arrays in TypeScript?

Real-World Example: Checking for Empty Search Results

Let’s consider a real-world scenario where you need to check if an array of search results is empty. In this example, we’ll use a hypothetical e-commerce website that allows users to search for products. Here is the complete TypeScript code.

interface Product {
  id: number;
  name: string;
  price: number;
}

function displaySearchResults(results: Product[]) {
  if (results.length === 0) {
    console.log("No products found matching your search.");
  } else {
    console.log(`Found ${results.length} products:`);
    results.forEach((product) => {
      console.log(`- ${product.name} ($${product.price})`);
    });
  }
}

const searchResults: Product[] = [
  { id: 1, name: "iPhone 13", price: 999 },
  { id: 2, name: "MacBook Pro", price: 1999 },
];

displaySearchResults(searchResults);

In this example, we define an interface called Product that represents a product with an id, name, and price. We then have a function called displaySearchResults that takes an array of Product objects as a parameter.

Inside the function, we check if the length of the results array is 0. If it is, we log the message “No products found matching your search.” This indicates that the search query didn’t yield any results.

If the results array is not empty, we log the number of products found using results.length. We then use the forEach method to iterate over each product in the results array and log its name and price.

Finally, we call the displaySearchResults function with an array called searchResults that contains two sample products.

We provide a user-friendly message when no products match the search query by checking for an empty array before displaying the search results.

Conclusion

In this tutorial, we explored various ways to check if an array is empty in TypeScript. We covered using the length property, combining Array.isArray() with length, and guarding against empty arrays using type guards. Do let me know if you still have any questions.

You may also like: