TypeScript Arrays
An array stores multiple values in a single variable, organized in a specific order. TypeScript arrays require all items to match a declared type. This prevents mixing numbers and strings in the same array accidentally, which eliminates an entire category of bugs found in JavaScript applications.
What Is a Typed Array?
JavaScript array (no type enforcement): +------+--------+------+-------+ | 42 | "Riya" | true | null | ← Mixed types allowed — risky +------+--------+------+-------+ TypeScript array (type enforced): +------+------+------+------+ | 85 | 92 | 78 | 95 | ← Only numbers allowed — safe +------+------+------+------+ scores: number[]
Declaring Arrays
TypeScript supports two syntaxes for declaring typed arrays. Both work identically — choose the one that feels more readable.
// Syntax 1: type followed by [] let scores: number[] = [85, 92, 78, 95]; let names: string[] = ["Aisha", "Vikram", "Pooja"]; let flags: boolean[] = [true, false, true]; // Syntax 2: Array generic syntax let scores2: Array<number> = [85, 92, 78, 95]; let names2: Array<string> = ["Aisha", "Vikram", "Pooja"];
Accessing Array Elements
Array elements are accessed by their index. Index counting starts at 0.
let fruits: string[] = ["Mango", "Apple", "Banana", "Grapes"]; // Index: [0] [1] [2] [3] console.log(fruits[0]); // Mango console.log(fruits[2]); // Banana console.log(fruits[3]); // Grapes
Array Length
let cities: string[] = ["Delhi", "Mumbai", "Chennai"]; console.log(cities.length); // 3
Adding and Removing Elements
let marks: number[] = [70, 80, 90]; // Add to the end marks.push(95); console.log(marks); // [70, 80, 90, 95] // Remove from the end marks.pop(); console.log(marks); // [70, 80, 90] // Add to the beginning marks.unshift(65); console.log(marks); // [65, 70, 80, 90] // Remove from the beginning marks.shift(); console.log(marks); // [70, 80, 90]
Looping Through Arrays
let students: string[] = ["Raj", "Sima", "Aryan", "Divya"];
// for loop
for (let i = 0; i < students.length; i++) {
console.log(i + ". " + students[i]);
}
// for...of loop (cleaner)
for (let student of students) {
console.log("Student: " + student);
}
// forEach method
students.forEach((student, index) => {
console.log(index + 1 + ". " + student);
});
Common Array Methods
| Method | What It Does | Example |
|---|---|---|
push() | Adds item to end | arr.push(10) |
pop() | Removes last item | arr.pop() |
unshift() | Adds item to beginning | arr.unshift(5) |
shift() | Removes first item | arr.shift() |
indexOf() | Finds index of a value | arr.indexOf(10) |
includes() | Checks if value exists | arr.includes(10) |
slice() | Extracts a portion | arr.slice(1, 3) |
splice() | Inserts or removes at position | arr.splice(1, 1) |
map() | Transforms each item | arr.map(x => x * 2) |
filter() | Keeps items matching condition | arr.filter(x => x > 5) |
find() | Returns first matching item | arr.find(x => x > 5) |
reduce() | Accumulates all items into one value | arr.reduce((a, b) => a + b, 0) |
map, filter, and reduce Examples
let examMarks: number[] = [55, 82, 91, 45, 73, 60];
// map — create a new array with each mark doubled (for practice test)
let doubledMarks = examMarks.map(mark => mark * 2);
console.log(doubledMarks);
// [110, 164, 182, 90, 146, 120]
// filter — keep only passing marks (>= 60)
let passingMarks = examMarks.filter(mark => mark >= 60);
console.log(passingMarks);
// [82, 91, 73, 60]
// reduce — calculate total
let totalMarks = examMarks.reduce((sum, mark) => sum + mark, 0);
console.log("Total: " + totalMarks);
// Total: 406
Multidimensional Arrays
A multidimensional array is an array where each element is also an array. This represents grid-like structures such as a table or a seating plan.
Seating Chart (rows × seats):
Row 0: [A1, A2, A3]
Row 1: [B1, B2, B3]
Row 2: [C1, C2, C3]
let seats: string[][] = [
["A1", "A2", "A3"],
["B1", "B2", "B3"],
["C1", "C2", "C3"]
];
console.log(seats[0][1]); // A2 (row 0, seat 1)
console.log(seats[2][0]); // C1 (row 2, seat 0)
Readonly Arrays
A readonly array cannot have items added, removed, or replaced after creation. This is useful for fixed lists like country codes or configuration values.
const DAYS: readonly string[] = ["Mon", "Tue", "Wed", "Thu", "Fri"];
console.log(DAYS[0]); // Mon
DAYS.push("Sat"); // Error: Property 'push' does not exist on type 'readonly string[]'
DAYS[0] = "Sunday"; // Error: Index signature in type 'readonly string[]' only permits reading
Practical Example
// Quiz score manager
let quizScores: number[] = [70, 85, 90, 60, 75, 88];
let passingScores: number[] = quizScores.filter(score => score >= 70);
let averageScore: number = quizScores.reduce((a, b) => a + b, 0) / quizScores.length;
let highestScore: number = Math.max(...quizScores);
console.log("All Scores: " + quizScores);
// All Scores: 70,85,90,60,75,88
console.log("Passing Scores: " + passingScores);
// Passing Scores: 70,85,90,75,88
console.log("Average: " + averageScore.toFixed(1));
// Average: 78.0
console.log("Highest: " + highestScore);
// Highest: 90
