Accessing object properties in Javascript - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Accessing a single property in an object.
- How many times: Once in this example.
Accessing a property takes about the same time no matter how many properties the object has.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays constant even if the object grows bigger.
Time Complexity: O(1)
This means accessing a property takes the same amount of time no matter how big the object is.
[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.
Understanding that property access is fast helps you reason about code performance and write efficient programs.
"What if we accessed a property inside a nested object? How would the time complexity change?"