0
0
Javascriptprogramming~5 mins

Object creation in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Object creation
O(n)
Understanding Time Complexity

Let's explore how the time it takes to create objects changes as we create more of them.

We want to know how the work grows when making many objects.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const createObjects = (n) => {
  const result = [];
  for (let i = 0; i < n; i++) {
    const obj = { id: i, value: i * 2 };
    result.push(obj);
  }
  return result;
};
    

This code creates an array of n objects, each with two properties.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating one object inside the loop.
  • How many times: Exactly n times, once per loop iteration.
How Execution Grows With Input

Each time we increase n, we create more objects one after another.

Input Size (n)Approx. Operations
1010 objects created
100100 objects created
10001000 objects created

Pattern observation: The work grows directly with n; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to create objects grows in a straight line with the number of objects.

Common Mistake

[X] Wrong: "Creating many objects is instant and does not depend on how many we make."

[OK] Correct: Each object takes some time to make, so more objects mean more total time.

Interview Connect

Understanding how object creation scales helps you write efficient code and explain your reasoning clearly in interviews.

Self-Check

"What if we added a nested loop inside to create objects inside objects? How would the time complexity change?"