Arrays in TypeScript
Learn how to declare arrays, specify element types, access and update elements, iterate through arrays, and work with multidimensional arrays in TypeScript.
What Is an Array?
An array is an ordered collection of values. Instead of creating separate variables for every course, student name, or mark, we can store related values together in an array.
TypeScript provides array type annotations so that elements can be checked against the expected data type.
- An array can contain multiple values.
- Array indexes start from 0.
-
The
lengthproperty returns the number of elements. - Elements can be accessed and updated using indexes.
- Array methods can be used to add, remove, search, and process elements.
Array Workflow
Follow these steps to understand how an array is created and used in a TypeScript program.
Step 1
Declare ArrayDefine the array and its element type.
Step 2
Store ValuesAdd values to the collection.
Step 3
Access ElementsRead or update values using indexes.
Step 4
Process DataIterate or perform array operations.
Example: Array Index Positions
Java
Python
.NET
Array: ["Java", "Python", ".NET"] — its length is 3.
1. Declaring an Array in TypeScript
TypeScript supports two common syntaxes for declaring arrays with a specific element type.
Syntax
let arrayName: type[] = [value1, value2, value3];
// Alternative syntax
let anotherArray: Array<type> = [value1, value2, value3];
Example
let courses: string[] = [
"Java",
"Python",
".NET"
];
let marks: number[] = [75, 80, 90];
console.log(courses);
console.log(marks);
Expected Output
[ 'Java', 'Python', '.NET' ]
[ 75, 80, 90 ]
Explanation
-
string[]represents an array of strings. -
number[]represents an array of numbers. -
Array<type>is an alternative generic syntax for declaring an array.
2. Accessing Array Elements
We can access an array element using its index. The first element has index 0, the second has index 1, and the third has index 2.
Example
let courses: string[] = [
"Java",
"Python",
".NET"
];
console.log(courses[0]);
console.log(courses[1]);
console.log(courses[2]);
Expected Output
Java
Python
.NET
Explanation
-
courses[0]accesses Java. -
courses[1]accesses Python. -
courses[2]accesses .NET.
3. Updating Array Elements
We can change an existing array element by assigning a new value to its index, provided the new value matches the array's element type.
Example
let courses: string[] = [
"Java",
"Python",
".NET"
];
courses[1] = "TypeScript";
console.log(courses);
Expected Output
[ 'Java', 'TypeScript', '.NET' ]
Explanation
The statement courses[1] = "TypeScript"
replaces the value at index 1. The other array
elements remain unchanged.
4. Array Length Property
The length property returns the number
of elements currently in an array.
Example
let courses: string[] = [
"Java",
"Python",
".NET",
"TypeScript"
];
console.log("Number of Courses:", courses.length);
Expected Output
Number of Courses: 4
Explanation
The array contains four elements, so
courses.length returns 4. Remember that
the number of elements and the last index are different:
for a non-empty array, the last index is
length - 1.
5. Iterating Through an Array
Iteration allows us to process array elements one by one. A for loop is useful when we need to work with element indexes.
Example
let courses: string[] = [
"Java",
"Python",
".NET"
];
for (let i: number = 0; i < courses.length; i++) {
console.log(courses[i]);
}
Expected Output
Java
Python
.NET
Explanation
- The loop starts at index 0.
- The condition checks whether the index is less than the array length.
- Each iteration displays one element.
- The loop stops when the index reaches the array length.
6. Using For Of with Arrays
The for...of loop provides a simple way
to iterate directly over array values without
manually managing an index.
Example
let marks: number[] = [75, 80, 90];
for (const mark of marks) {
console.log(mark);
}
Expected Output
75
80
90
Explanation
In each iteration, the mark variable
receives the next element in the array.
Use for...of when you need the values;
use an indexed loop when you also need the index.
7. Multidimensional Arrays
An array can contain other arrays. This structure is useful for representing rows and columns, such as a table of marks.
Example
let marks: number[][] = [
[75, 80, 85],
[90, 88, 92]
];
console.log(marks[0][0]);
console.log(marks[0][1]);
console.log(marks[1][2]);
Expected Output
75
80
92
Visual Representation
| Row / Index | Column 0 | Column 1 | Column 2 |
|---|---|---|---|
| Row 0 | 75 | 80 | 85 |
| Row 1 | 90 | 88 | 92 |
The first index selects the inner array, and the second index selects an element inside that array.
8. Readonly Arrays
A readonly array prevents adding, removing, or replacing elements through that readonly reference. It is useful when an array should only be read.
Example
const courses: readonly string[] = [
"Java",
"Python",
".NET"
];
console.log(courses[0]);
console.log(courses.length);
Expected Output
Java
3
Important Point
// TypeScript compile-time error:
courses.push("TypeScript");
// TypeScript compile-time error:
courses[0] = "C#";
These modifications are rejected by TypeScript's type checker. A readonly array reference does not by itself guarantee deep immutability of nested objects.
9. Array Type Syntax Comparison
| Syntax | Meaning | Example |
|---|---|---|
string[] |
Array of strings | ["Java", "Python"] |
number[] |
Array of numbers | [10, 20, 30] |
boolean[] |
Array of boolean values | [true, false] |
Array<string> |
Generic syntax for an array of strings | ["Java", "Python"] |
number[][] |
Array of numeric arrays | [[1, 2], [3, 4]] |
10. Practical Example: CIIT Student Marks
Let's create an array of student marks, calculate their total, and determine the average.
Example
let marks: number[] = [85, 90, 78, 92, 88];
let total: number = 0;
for (const mark of marks) {
total += mark;
}
const average: number = total / marks.length;
console.log("Total Marks:", total);
console.log("Number of Subjects:", marks.length);
console.log("Average Marks:", average);
Expected Output
Total Marks: 433
Number of Subjects: 5
Average Marks: 86.6
Explanation
- The marks array stores five numeric values.
- The loop adds all marks to the total.
- The length property returns the number of subjects.
- The average is calculated by dividing the total by the number of subjects.
Common Mistakes
- Using index 1 to access the first element instead of index 0.
- Accessing an index outside the array's valid range.
- Assigning a value that does not match the array element type.
- Confusing the array length with its last index.
- Trying to modify a readonly array.
- Forgetting to handle empty arrays when calculating averages or other derived values.
Practice Task
Write TypeScript programs to complete the following tasks.
- Create an array of five programming language names and display each element.
- Add a new element and update an existing array element.
- Find the total and average of an array of marks.
- Create a two-dimensional array containing marks for two students.
- Declare a readonly array and identify which operations the TypeScript compiler rejects.
Summary
In this lesson, we learned how to declare typed arrays, access and update elements, use the length property, iterate with for and for...of loops, and create multidimensional and readonly arrays. We also calculated total and average student marks using a practical example.