readonly arrays
- TypeScript course
- Beginner
- Lesson 13/89
- 4 min
Learn the immutability of readonly arrays.
readonly arrays
The readonly modifier marks an array as immutable. With readonly number[], you cannot add or remove elements via push, pop, etc.; the array is read-only. This prevents accidental data changes.
let sabit: readonly number[] = [1, 2, 3];
// sabit.push(4); // Error
console.log(sabit[0]); // 1readonly vs normal array
A normal number[] is mutable; a readonly number[] is not. TypeScript warns even when assigning a readonly array to a normal array, because a mutable copy can break data integrity. Readonly is especially useful in function parameters to protect data.
function goster(d: readonly number[]) {
// d.push(5); // Error
return d[0];
}Practice Days array
Define a readonly string[] array named gunler with the values "pzt", "sal", "çar". Then print the array with console.log.
Starter code
// readonly string dizisi tanımla ve yazdırSample solution
let gunler: readonly string[] = ["pzt", "sal", "çar"];
console.log(gunler);Expected output
[ 'pzt', 'sal', 'çar' ]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which operation is valid on an array declared as `readonly string[]`?
- Changing the first element of the array
- Shrinking the array with pop
- Adding an element with push
- Reading the array (e.g. sabit[0]) Correct answer
Explanation: A readonly array can only be read; `push`, `pop` and element assignment give compile errors.
2 Define a readonly array
let puanlar: ____ = [90, 85, 70];
let puanlar: readonly number[] = [90, 85, 70];
Explanation: `readonly number[]` defines an immutable number array; writing just `number[]` or `Array<number>` does not add readonly protection.
3 readonly behaviors
| Term | Meaning |
|---|---|
readonly number[] |
Immutable number array |
number[] |
Mutable number array |
sabit.push(4) |
Errors on a readonly array |
sabit[0] |
Valid on a readonly array |