Menu
Coddy logo textTech

'readonly' Modifier for Arrays

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 14 of 73.

TypeScript provides the readonly modifier for arrays, which prevents any changes to the array's contents once it's created.

When you add readonly before an array type, TypeScript ensures that you cannot add, remove, or modify elements. This creates an immutable data structure that's perfect for configuration data, constants, or any situation where you want to guarantee the array won't change.

let colors: readonly string[] = ["red", "green", "blue"];
let numbers: readonly number[] = [1, 2, 3, 4, 5];

The readonly modifier blocks all mutating operations like push(), pop(), splice(), and direct index assignment. If you try to use these methods, TypeScript will show a compile-time error, preventing potential bugs before your code runs.

challenge icon

Challenge

Easy

Create a readonly array named configValues that can only hold strings and initialize it with the values "production", "database", and "cache".

Then create another readonly array named ports that can only hold numbers and initialize it with the values 3000, 5432, and 6379.

Finally, create a readonly array named features that can only hold boolean values and initialize it with true, false, and true.

Print all three readonly arrays to the console on separate lines in the order they were created.

Try it yourself

// TODO: Write your code here
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript