TypeScript Arrays - A Step-by-Step Guide


Introduction

Arrays are a fundamental data structure in TypeScript that allow you to store collections of values. They are versatile and widely used in programming. In this guide, we'll explore how to work with arrays in TypeScript.


Creating Arrays

You can create arrays in TypeScript using various methods.


Using Array Literals

You can use square brackets to define an array literal:

let numbers: number[] = [1, 2, 3, 4, 5];

Using the Array Constructor

You can also use the Array constructor:

let fruits: Array<string> = new Array("apple", "banana", "cherry");

Accessing Array Elements

You can access array elements by their index.


Example:

let colors: string[] = ["red", "green", "blue"];
let firstColor: string = colors[0]; // "red"

Array Properties and Methods

Arrays have various properties and methods for manipulation.


length Property

The length property returns the number of elements in an array:

let numbers: number[] = [1, 2, 3, 4, 5];
let count: number = numbers.length; // 5

push() Method

The push() method adds one or more elements to the end of an array:

let fruits: string[] = ["apple", "banana"];
fruits.push("cherry");

pop() Method

The pop() method removes the last element from an array and returns it:

let numbers: number[] = [1, 2, 3, 4, 5];
let lastNumber: number = numbers.pop(); // 5

Iterating Over Arrays

You can loop through arrays using for loops or array methods like forEach().


Using a for Loop

let colors: string[] = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}

Using forEach()

let fruits: string[] = ["apple", "banana", "cherry"];
fruits.forEach(function (fruit) {
console.log(fruit);
});

Conclusion

Arrays are a crucial part of TypeScript, providing a way to store and manipulate collections of data. Understanding how to create, access, and work with arrays is essential for developing TypeScript applications. As you progress in your TypeScript journey, explore more advanced array operations and data manipulation techniques.