How to Find the Length of an Array in TypeScript?

In this tutorial, I will explain how to find the length of an array in TypeScript. As a developer, you may often need to determine the number of elements in an array for various purposes, such as iterating over the array, checking if the array is empty, or performing specific operations based on the array size. TypeScript provides a straightforward way to obtain the length of an array using the length property.

Understanding the length Property in TypeScript

In TypeScript, arrays have a built-in property called length that returns the number of elements in the array. The length property is a read-only property, which means you cannot modify its value directly. It is automatically updated whenever elements are added or removed from the array.

Here’s an example that demonstrates how to access the length property of an array in TypeScript:

const fruits: string[] = ['Apple', 'Banana', 'Orange'];
console.log(fruits.length); // Output: 3

In this example, we have an array called fruits that contains three elements. By accessing the length property using fruits.length, we get the value 3, indicating that the array has three elements.

Here is the exact output in the screenshot below:

Find the Length of an Array in TypeScript

Check out How to Remove an Item from an Array in TypeScript?

Real-World Example: User Management System

Let’s consider a real-world scenario where you are building a user management system for a company based in the USA. You have an array of user objects, and you need to perform certain actions based on the number of users in the system.

interface User {
  id: number;
  name: string;
  email: string;
}

const users: User[] = [
  { id: 1, name: 'John Doe', email: 'john@example.com' },
  { id: 2, name: 'Jane Smith', email: 'jane@example.com' },
  { id: 3, name: 'Michael Johnson', email: 'michael@example.com' },
];

console.log('Number of users:', users.length);

In this example, we have an interface User that defines the structure of a user object. We then create an array called users that contains three user objects. By using users.length, we can easily obtain the number of users in the system, which is 3 in this case.

Here is the exact output in the screenshot below:

Get the Length of an Array in TypeScript

Checking if the Array is Empty

One common use case for the length property is to check if an array is empty. You can simply compare the length property to zero to determine if the array has no elements.

const employees: string[] = [];

if (employees.length === 0) {
  console.log('No employees found.');
} else {
  console.log('Number of employees:', employees.length);
}

In this example, we have an empty array called employees. By checking if employees.length is equal to zero, we can determine that the array is empty and display a message accordingly. If the array is not empty, we can proceed to display the number of employees.

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

Iterating Over the Array

Another common scenario where the length property is useful is when you need to iterate over an array. You can use a for loop or other iteration methods to access each element of the array based on its length.

const states: string[] = ['California', 'New York', 'Texas', 'Florida'];

for (let i = 0; i < states.length; i++) {
  console.log(`State ${i + 1}: ${states[i]}`);
}

In this example, we have an array called states that contains the names of some states in the USA. By using a for loop and the length property, we can iterate over each element of the array and display its index and value.

Check out How to Iterate Over Arrays in TypeScript?

Performing Operations Based on Array Length

The length property can also be used to perform specific operations based on the size of the array. For example, you may want to apply different logic depending on the number of elements in the array.

const products: string[] = ['Laptop', 'Smartphone', 'Headphones'];

if (products.length >= 3) {
  console.log('Applying discount for purchasing 3 or more products.');
} else {
  console.log('No discount applied.');
}

In this example, we have an array called products that represents a list of items in an online store. If the number of products in the array is greater than or equal to 3, we display a message indicating that a discount will be applied. Otherwise, no discount is applied.

Conclusion

In TypeScript, the length property is used for determining the number of elements in an array. It provides a simple and efficient way to obtain the size of an array, which is essential for various operations such as checking if an array is empty, iterating over its elements, or performing specific actions based on the array length.

The length property is a read-only property that returns the number of elements in an array as an unsigned 32-bit integer. It is automatically updated whenever the array is modified.

So, the next time you encounter a scenario where you need to determine the length of an array in TypeScript, remember to utilize the length property.

You may also like: