Void type for functions in Typescript - Time & Space Complexity
Let's see how the time it takes to run a function with a void return type changes as input grows.
We want to know how the function's work grows with bigger inputs.
Analyze the time complexity of the following code snippet.
function printNumbers(n: number): void {
for (let i = 0; i < n; i++) {
console.log(i);
}
}
This function prints numbers from 0 up to n-1 and returns nothing (void).
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs console.log for each number.
- How many times: Exactly n times, once for each number from 0 to n-1.
As n grows, the number of print actions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print actions |
| 100 | 100 print actions |
| 1000 | 1000 print actions |
Pattern observation: The work grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the function takes longer in a straight line as the input number gets bigger.
[X] Wrong: "Since the function returns void, it must run instantly or have no cost."
[OK] Correct: The return type only says what the function gives back, not how long it takes. The loop still runs n times, so the time grows with n.
Understanding how loops affect time, even in functions that return nothing, helps you explain your code clearly and think about efficiency.
"What if we changed the loop to run only half of n times? How would the time complexity change?"