Object entries in Javascript - Time & Space Complexity
We want to understand how long it takes to get all key-value pairs from an object using Object.entries.
How does the time grow when the object has more properties?
Analyze the time complexity of the following code snippet.
const obj = { a: 1, b: 2, c: 3 };
const entries = Object.entries(obj);
for (const [key, value] of entries) {
console.log(key, value);
}
This code gets all key-value pairs from an object and prints them one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through all entries of the object.
- How many times: Once for each property in the object.
As the number of properties grows, the time to get and loop through entries grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 operations |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: The work grows in a straight line with the number of properties.
Time Complexity: O(n)
This means the time to get all entries grows directly with the number of properties.
[X] Wrong: "Object.entries is instant no matter how big the object is."
[OK] Correct: Actually, it must look at every property to make the list, so bigger objects take more time.
Knowing how Object.entries works helps you explain performance when working with objects in real projects.
"What if we used Object.keys instead of Object.entries? How would the time complexity change?"