Why arrays are needed in Javascript - Performance Analysis
We want to understand why arrays are useful by looking at how they help us handle many items efficiently.
How does using an array affect the time it takes to find or store items as the list grows?
Analyze the time complexity of searching for a value in an array.
const numbers = [3, 7, 1, 9, 5];
function findNumber(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i;
}
}
return -1;
}
findNumber(numbers, 9);
This code looks through an array to find the position of a target number.
Look at what repeats as the array grows.
- Primary operation: Checking each item one by one in the array.
- How many times: Up to once for every item in the array until the target is found or the end is reached.
As the array gets bigger, the search takes longer because it may check more items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows directly with the number of items.
Time Complexity: O(n)
This means the time to find an item grows in a straight line with the number of items.
[X] Wrong: "Searching an array always takes the same time no matter how big it is."
[OK] Correct: Because the search may need to look at many items, bigger arrays usually take longer to search.
Understanding how arrays work helps you explain why choosing the right data structure matters for speed and efficiency.
"What if we used a different data structure like an object or a set instead of an array? How would the time complexity change?"