Object use cases in Javascript - Time & Space Complexity
When using objects in JavaScript, it's important to know how fast operations like adding, accessing, or checking properties happen.
We want to understand how the time to do these tasks changes as the object grows bigger.
Analyze the time complexity of the following code snippet.
const obj = {};
for (let i = 0; i < n; i++) {
obj[`key${i}`] = i;
}
const value = obj['key500'];
const hasKey = 'key500' in obj;
This code adds n properties to an object, then accesses and checks one property.
- Primary operation: Adding properties inside a loop.
- How many times: n times, once per loop iteration.
- Accessing and checking a property happens once each, outside the loop.
Adding properties grows with the number of items n, but accessing or checking a property stays quick no matter the size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions, 1 access, 1 check |
| 100 | 100 additions, 1 access, 1 check |
| 1000 | 1000 additions, 1 access, 1 check |
Pattern observation: Adding properties grows linearly with n, but accessing or checking a property stays constant time.
Time Complexity: O(n)
This means adding n properties takes time proportional to n, but accessing or checking a property is very fast and does not depend on n.
[X] Wrong: "Accessing a property in an object takes longer as the object gets bigger."
[OK] Correct: Objects use a special way to find properties quickly, so access time stays about the same no matter how many properties there are.
Understanding how objects work behind the scenes helps you write faster code and answer questions about efficiency with confidence.
"What if we used an array instead of an object to store these key-value pairs? How would the time complexity change?"
Practice
Solution
Step 1: Understand what an object stores
Objects store data as pairs of keys (labels) and values, grouping related information.Step 2: Compare options to definition
A collection of key-value pairs to store related data matches this definition exactly, while others describe different concepts.Final Answer:
A collection of key-value pairs to store related data -> Option DQuick Check:
Object = key-value pairs [OK]
- Confusing objects with arrays (which are ordered lists)
- Thinking objects are only functions
- Mixing up objects with loops or other structures
Solution
Step 1: Recall object literal syntax
Objects use curly braces with key: value pairs, like {key: value}.Step 2: Check each option's syntax
let obj = {name: 'Alice'}; uses correct curly braces and colon. Others use invalid syntax for JavaScript objects.Final Answer:
let obj = {name: 'Alice'}; -> Option BQuick Check:
Object syntax = {key: value} [OK]
- Using parentheses instead of braces
- Using arrow => which is not valid in JS objects
- Omitting braces entirely
const car = { brand: 'Toyota', year: 2020 };
console.log(car.brand);Solution
Step 1: Access the 'brand' property of the object
car.brand accesses the value stored under the key 'brand', which is 'Toyota'.Step 2: Understand console.log output
console.log prints the value Toyota to the console.Final Answer:
Toyota -> Option AQuick Check:
car.brand = Toyota [OK]
- Printing the key name instead of the value
- Using wrong property name causing undefined
- Confusing object with array indexing
const person = { name: 'Bob', age: 25 };
console.log(person['age']);
console.log(person.age());Solution
Step 1: Identify property types in the object
person has keys 'name' and 'age' with values 'Bob' and 25 (a number), not functions.Step 2: Check method call usage
person.age() tries to call age as a function, but age is a number, causing an error.Final Answer:
person.age() is incorrect because age is not a function -> Option AQuick Check:
Only functions can be called with () [OK]
- Calling a number or string as a function
- Confusing bracket and dot notation usage
- Assuming missing semicolons cause runtime errors
Solution
Step 1: Identify need for data and method together
We want to store multiple students with scores and a method to calculate average, so an object with a list and a function is suitable.Step 2: Evaluate each option
const students = { list: [{name: 'Anna', score: 90}, {name: 'Ben', score: 80}], average: function() { /* calculate average */ } }; uses an object with a list of student objects and a method for average calculation. const students = ['Anna', 90, 'Ben', 80]; is a flat array without structure. const students = { 'Anna': 90, 'Ben': 80 }; lacks a method. const students = function() { return ['Anna', 90, 'Ben', 80]; }; is a function, not an object with data and method.Final Answer:
const students = { list: [{name: 'Anna', score: 90}, {name: 'Ben', score: 80}], average: function() { /* calculate average */ } }; -> Option CQuick Check:
Object with data + method = const students = { list: [{name: 'Anna', score: 90}, {name: 'Ben', score: 80}], average: function() { /* calculate average */ } }; [OK]
- Using arrays without methods for complex data
- Not grouping related data in objects
- Confusing functions with data containers
Ready to prove it?
Pass the test and this pattern moves unknown
