Arrays and linked lists are both ways to store collections of items. Why do arrays allow you to get any item quickly, while linked lists do not?
Think about how memory addresses work and how you find an element's location.
Arrays store elements one after another in memory. This means you can find the address of any element by adding its index times the size of each element to the start address. Linked lists store elements scattered in memory with pointers, so you must follow links one by one.
Consider this TypeScript code that inserts elements into an array. What will be printed?
const arr: number[] = []; arr.push(10); arr.push(20); arr[1] = 30; console.log(arr);
Remember that assigning to an existing index replaces the value.
Initially, arr is empty. push(10) adds 10 at index 0. push(20) adds 20 at index 1. Then arr[1] = 30 replaces the value at index 1 (which was 20) with 30. So the array is [10, 30].
What happens when you try to access an index that does not exist in a TypeScript array?
const arr = [1, 2, 3]; console.log(arr[5]);
Think about what JavaScript/TypeScript returns when accessing missing indexes.
Accessing an index outside the array length returns undefined in JavaScript and TypeScript. It does not throw an error or return null or zero.
Look at this code snippet. Why does the output not show the expected updated array?
const arr = [1, 2, 3]; function updateArray(a: number[]) { a = [4, 5, 6]; } updateArray(arr); console.log(arr);
Consider how assignment inside a function affects the original array.
Inside the function, the parameter 'a' is assigned a new array, but this does not change the original array 'arr' outside the function. The original array remains unchanged, so console.log(arr) prints [1, 2, 3].
Imagine you are building a music player app that needs to quickly access songs by their position in a playlist. Why is using an array a good choice for storing the playlist?
Think about how you find a song by its position in the playlist.
Arrays store elements in order and allow direct access by index, so the app can quickly jump to any song without searching. This makes playback smooth and responsive.
