0
0
Javascriptprogramming~5 mins

Why objects are needed in Javascript - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why objects are needed
O(1)
Understanding Time Complexity

We want to understand why using objects in JavaScript matters for how fast our code runs.

Specifically, we ask: how does using objects affect the number of steps our program takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const person = { name: "Alice", age: 30, city: "NY" };

function getAge(obj) {
  return obj.age;
}

console.log(getAge(person));
    

This code creates an object with some details and then gets the age from it.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Accessing a property from an object.
  • How many times: Once per call to getAge.
How Execution Grows With Input

Getting a property from an object takes about the same time no matter how many properties the object has.

Input Size (n)Approx. Operations
3 properties1 step
10 properties1 step
100 properties1 step

Pattern observation: Access time stays about the same even if the object grows bigger.

Final Time Complexity

Time Complexity: O(1)

This means accessing a property from an object takes a constant amount of time, no matter the object size.

Common Mistake

[X] Wrong: "Accessing a property gets slower as the object has more properties."

[OK] Correct: JavaScript engines use optimized data structures (like hidden classes and hash maps) to find properties quickly, so access time stays fast even if the object is big.

Interview Connect

Knowing that objects give quick access to data helps you write efficient code and explain your choices clearly in interviews.

Self-Check

"What if we stored data in an array instead of an object? How would the time complexity of accessing a value change?"