Challenge - 5 Problems
Read-only Arrays Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this TypeScript code using a readonly array?
Consider the following TypeScript code. What will be printed to the console?
Typescript
const nums: readonly number[] = [1, 2, 3]; // nums.push(4); // This line is commented out console.log(nums[1]);
Attempts:
2 left
💡 Hint
Readonly arrays allow reading elements but not modifying them.
✗ Incorrect
The readonly array nums contains [1, 2, 3]. Accessing nums[1] returns 2. The push method is not called because it is commented out.
❓ Predict Output
intermediate2:00remaining
What error does this code raise when trying to modify a readonly array?
What error will this TypeScript code produce when compiled?
Typescript
const letters: readonly string[] = ['a', 'b', 'c']; letters[0] = 'z';
Attempts:
2 left
💡 Hint
Readonly arrays prevent assignment to elements.
✗ Incorrect
TypeScript compiler will show an error because you cannot assign a value to an index of a readonly array.
🔧 Debug
advanced2:00remaining
Why does this code fail to compile when using readonly arrays?
Identify the reason why this TypeScript code does not compile.
Typescript
function addItem(arr: readonly number[], item: number) { arr.push(item); return arr; }
Attempts:
2 left
💡 Hint
Readonly arrays do not allow modification methods.
✗ Incorrect
Readonly arrays do not have mutating methods like push, so calling push causes a compile error.
🧠 Conceptual
advanced2:00remaining
Which statement about readonly arrays in TypeScript is true?
Choose the correct statement about readonly arrays.
Attempts:
2 left
💡 Hint
Think about what readonly means for arrays.
✗ Incorrect
Readonly arrays prevent any modification to their elements or structure, including reassignment of elements and use of mutating methods like push or pop.
❓ Predict Output
expert2:00remaining
What is the output of this code mixing readonly and mutable arrays?
What will be the output of this TypeScript code?
Typescript
const original: number[] = [1, 2, 3]; const readOnlyView: readonly number[] = original; original.push(4); console.log(readOnlyView.length);
Attempts:
2 left
💡 Hint
Readonly arrays are views, not copies.
✗ Incorrect
readOnlyView references the same array as original. Pushing to original changes the array length, so readOnlyView.length is 4.