0
0
Javascriptprogramming~5 mins

Accessing object properties in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Accessing object properties
O(1)
Understanding Time Complexity

When we access properties in an object, we want to know how long it takes as the object grows.

We ask: Does looking up a property take more time if the object has many properties?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const person = {
  name: 'Alice',
  age: 30,
  city: 'Wonderland'
};

const city = person.city;
console.log(city);
    

This code accesses the city property from the person object and prints it.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Accessing a single property in an object.
  • How many times: Once in this example.
How Execution Grows With Input

Accessing a property takes about the same time no matter how many properties the object has.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time stays constant even if the object grows bigger.

Final Time Complexity

Time Complexity: O(1)

This means accessing a property takes the same amount of time no matter how big the object is.

Common Mistake

[X] Wrong: "Accessing a property takes longer if the object has more properties."

[OK] Correct: JavaScript engines use fast methods to find properties, so the time does not grow with object size.

Interview Connect

Understanding that property access is fast helps you reason about code performance and write efficient programs.

Self-Check

"What if we accessed a property inside a nested object? How would the time complexity change?"