Imagine you want to keep a list of your favorite books. Which problem does using an array solve compared to using separate variables for each book?
Think about how you would find the 3rd book if you had 10 separate variables versus one list.
Arrays group multiple items together so you can store and access them by their position (index). This avoids creating many separate variables and makes managing lists easier.
Look at this JavaScript code and find the output of the console.log statement.
const fruits = ['apple', 'banana', 'cherry']; console.log(fruits[1]);
Remember, array indexes start at 0.
The array fruits has 'apple' at index 0, 'banana' at index 1, and 'cherry' at index 2. Accessing fruits[1] returns 'banana'.
Consider this JavaScript code. What will be the printed array after adding a new item?
const colors = ['red', 'green', 'blue']; colors.push('yellow'); console.log(colors);
Think about what the push method does to an array.
The push method adds the new item to the end of the array. So the array now has four items with 'yellow' at the end.
Look at this code and find why the output is undefined.
const numbers = [10, 20, 30]; console.log(numbers[3]);
Check how many items the array has and what indexes are valid.
The array has elements at indexes 0, 1, and 2. Accessing index 3 is out of range, so JavaScript returns undefined.
Arrays and linked lists both store collections of items. What is a key advantage of arrays over linked lists?
Think about how you find the 5th item in an array versus a linked list.
Arrays store items in continuous memory locations, so accessing by index is fast (direct). Linked lists require moving from one node to the next to reach a position.
