Type checking using typeof in Javascript - Time & Space Complexity
We want to understand how long it takes to check the type of a value using typeof in JavaScript.
Specifically, how does the time grow when we check many values?
Analyze the time complexity of the following code snippet.
const values = [1, 'hello', true, null, undefined, {}, []];
for (let i = 0; i < values.length; i++) {
console.log(typeof values[i]);
}
This code loops through an array and prints the type of each element using typeof.
- Primary operation: The
forloop that runstypeofon each element. - How many times: Once for each element in the array.
As the number of elements grows, the number of typeof checks grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 typeof checks |
| 100 | 100 typeof checks |
| 1000 | 1000 typeof checks |
Pattern observation: The work grows directly with the number of items; double the items, double the checks.
Time Complexity: O(n)
This means the time to check types grows in a straight line with the number of elements.
[X] Wrong: "Using typeof is instant and does not depend on the number of elements."
[OK] Correct: While one typeof is very fast, checking many elements means repeating it many times, so total time grows with the number of elements.
Understanding how simple operations like typeof scale helps you reason about performance in real code, showing you can think about efficiency clearly.
"What if we replaced the for loop with a recursive function calling typeof on each element? How would the time complexity change?"