How to Check if an Array is Not Empty in TypeScript?

In this tutorial, I will explain how to check if an array is not empty in TypeScript. When processing JSON responses or working with arrays in TypeScript, it’s important to know how to safely check if a variable is an array and is not empty. Let me explain the details with some real-world examples.

Using the Length Property

The easiest way to check if a TypeScript array is empty is to use the length property with the === operator. If the length is 0, the array is empty. Here’s an example:

const employees: string[] = ['John', 'Emily', 'Michael'];

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

In this example, we have an array called employees that contains the names of some employees in a US-based company. We check if the length of the array is equal to 0. If it is, we log the message “The array is empty”. Otherwise, we log the message “The array is not empty”.

Here is the exact output in the screenshot below:

Check if an Array is Not Empty in TypeScript

Check out How to Check if an Array is Empty in TypeScript?

Check for Undefined or Null

In some cases, you might encounter a situation where the array itself could be undefined or null. To handle such scenarios, you can use the && operator to first check if the array exists before checking its length. Here’s an example:

const customers: string[] | undefined = undefined;

if (customers && customers.length > 0) {
  console.log('The array is not empty');
} else {
  console.log('The array is empty or undefined');
}

In this example, we have a variable called customers that is of type string[] | undefined, meaning it can either be an array of strings or undefined. We first check if customers is truthy (not null or undefined) using the && operator.

If it is, we then check if the length of the array is greater than 0. If both conditions are true, we log the message “The array is not empty”. Otherwise, we log the message “The array is empty or undefined”.

Check out Declare and Initialize Empty Arrays in TypeScript

Using the filter() Method

Another approach to check if an array is empty in TypeScript is to use the filter() method. The filter() method creates a new array with all the elements that pass the test implemented by the provided callback function. If the resulting array has a length of 0, it means the original array is empty. Here’s an example:

const products: string[] = [];

if (products.filter(Boolean).length > 0) {
  console.log('The array is not empty');
} else {
  console.log('The array is empty');
}

In this example, we have an empty array called products. We use the filter() method with the Boolean function as the callback. The Boolean function will filter out any falsy values (like empty strings, 0, null, undefined) from the array.

If the resulting array has a length greater than 0, it means the original array is not empty. Otherwise, it means the array is empty.

Here is the exact output in the screenshot below:

How to Check if an Array is Not Empty in TypeScript

Read Create and Use an Empty String Array in TypeScript

Real-World Example

Let’s consider a real-world scenario where you are building an e-commerce application for a US-based company. You have an API endpoint that returns an array of products. However, sometimes, the API might return an empty array if no products are available. Here’s how you can handle this situation in TypeScript:

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

function displayProducts(products: Product[]) {
  if (products.length === 0) {
    console.log('No products available');
  } else {
    products.forEach(product => {
      console.log(`ID: ${product.id}, Name: ${product.name}, Price: $${product.price}`);
    });
  }
}

// API response with products
const apiProducts: Product[] = [
  { id: 1, name: 'iPhone 13', price: 999 },
  { id: 2, name: 'MacBook Pro', price: 1999 },
  { id: 3, name: 'iPad Air', price: 599 }
];

// API response with an empty array
const apiEmptyProducts: Product[] = [];

displayProducts(apiProducts);
displayProducts(apiEmptyProducts);

In this example, we define an interface called Product that represents the structure of a product object. We have a function called displayProducts that takes an array of Product objects as a parameter.

Inside the function, we check if the length of the products array is equal to 0. If it is, we log the message “No products available”. Otherwise, we use the forEach method to log the details of each product.

We have two scenarios: one where the API returns an array of products (apiProducts) and another where the API returns an empty array (apiEmptyProducts). We call the displayProducts function with both arrays to handle both scenarios gracefully.

Conclusion

In this tutorial, I explained different ways to check if an array is not empty in TypeScript. We covered using the length property, checking for undefined or null, and using the filter() method. We also looked at a real-world scenario of checking for an empty array in TypeScript.

You may also like: