let result = ''; for (let i = 0; i <= 3; i++) { result += i + ','; } console.log(result);
Look carefully at the loop condition i <= 3. It includes the number 3.
The loop runs while i is less than or equal to 3, so it includes 0, 1, 2, and 3. The output string concatenates these numbers with commas.
Think about what happens if you try to get an element at an index that does not exist.
Accessing an index outside the array length returns undefined in TypeScript, which can cause bugs if not handled properly.
function getLastElement(arr: number[]): number | undefined { return arr[arr.length - 1]; } console.log(getLastElement([]));
What is the value of arr.length - 1 when the array is empty?
When the array is empty, arr.length - 1 equals -1, so arr[-1] is undefined. No error is thrown, but the function returns undefined.
Remember array indexes start at 0 and go up to length - 1.
Option B correctly checks that the index is at least 0 and less than the array length, ensuring valid access.
const arr = [10, 20, 30]; let sum = 0; for (let i = 0; i <= arr.length; i++) { sum += arr[i] ?? 0; } console.log(sum);
Notice the loop runs one step beyond the last index. What does arr[i] return then?
The loop runs from 0 to 3 (inclusive). arr[3] is undefined, so arr[i] ?? 0 adds 0. The sum is 10 + 20 + 30 + 0 = 60.