Why functions are needed in Javascript - Performance Analysis
We want to see how using functions affects the time it takes for code to run.
Specifically, does breaking code into functions change how long it takes as input grows?
Analyze the time complexity of the following code snippet.
function printNumbers(n) {
for (let i = 0; i < n; i++) {
console.log(i);
}
}
printNumbers(5);
This code prints numbers from 0 up to n-1 using a function.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs once for each number from 0 to n-1.
- How many times: Exactly n times, where n is the input number.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The work grows directly with the input size; doubling n doubles the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[X] Wrong: "Using a function makes the code slower because it adds extra steps."
[OK] Correct: Functions organize code but do not change how many times the main work happens. The loop inside still runs n times, so the main time cost stays the same.
Understanding how functions affect time helps you write clear code without worrying about hidden slowdowns. This skill shows you can think about both code design and performance.
"What if the function called itself recursively instead of using a loop? How would the time complexity change?"