Array creation in Javascript - Time & Space Complexity
When we create an array in JavaScript, it's important to know how the time it takes grows as the array gets bigger.
We want to answer: How does the time to make an array change when we add more items?
Analyze the time complexity of the following code snippet.
const size = 1000;
const arr = new Array(size);
for (let i = 0; i < size; i++) {
arr[i] = i * 2;
}
This code creates an array of a given size and fills it with numbers doubled from their index.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that assigns values to each array element.
- How many times: It runs exactly once for each item, so
sizetimes.
As the array size grows, the number of assignments grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 assignments |
| 100 | 100 assignments |
| 1000 | 1000 assignments |
Pattern observation: The work grows directly with the number of items; double the size, double the work.
Time Complexity: O(n)
This means the time to create and fill the array grows in a straight line with the number of elements.
[X] Wrong: "Creating an array of size n is instant and does not depend on n."
[OK] Correct: Even if the array is created with a fixed size, filling each element takes time that grows with n.
Understanding how array creation time grows helps you explain performance when working with lists and data structures in real projects.
"What if we used Array.from() with a mapping function instead of a for-loop? How would the time complexity change?"