0
0
Javascriptprogramming~5 mins

Object keys and values in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Object keys and values
O(n)
Understanding Time Complexity

When working with objects in JavaScript, we often get their keys or values. Understanding how long this takes helps us write faster code.

We want to know how the time to get keys or values changes as the object grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const obj = {a: 1, b: 2, c: 3, d: 4};

const keys = Object.keys(obj);
const values = Object.values(obj);

console.log(keys);
console.log(values);
    

This code gets all the keys and values from an object and prints them.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: JavaScript internally loops over each property in the object to collect keys or values.
  • How many times: Once for each property in the object.
How Execution Grows With Input

As the object gets bigger, the time to get keys or values grows in a straight line with the number of properties.

Input Size (n)Approx. Operations
10About 10 steps to collect keys or values
100About 100 steps
1000About 1000 steps

Pattern observation: The work grows evenly as the object size grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to get all keys or values grows directly with the number of properties in the object.

Common Mistake

[X] Wrong: "Getting keys or values is instant no matter how big the object is."

[OK] Correct: JavaScript must look at each property to collect keys or values, so bigger objects take more time.

Interview Connect

Knowing how object operations scale helps you explain your code choices clearly and shows you understand how JavaScript works behind the scenes.

Self-Check

"What if we only needed the first key or value instead of all? How would the time complexity change?"