0
0
Javascriptprogramming~5 mins

Array creation in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Array creation
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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 size times.
How Execution Grows With Input

As the array size grows, the number of assignments grows the same way.

Input Size (n)Approx. Operations
1010 assignments
100100 assignments
10001000 assignments

Pattern observation: The work grows directly with the number of items; double the size, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to create and fill the array grows in a straight line with the number of elements.

Common Mistake

[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.

Interview Connect

Understanding how array creation time grows helps you explain performance when working with lists and data structures in real projects.

Self-Check

"What if we used Array.from() with a mapping function instead of a for-loop? How would the time complexity change?"