Function expression in Javascript - Time & Space Complexity
Let's see how the time it takes to run a function expression changes as we give it more work.
We want to know how the number of steps grows when the input gets bigger.
Analyze the time complexity of the following code snippet.
const sumArray = function(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
};
const numbers = [1, 2, 3, 4, 5];
console.log(sumArray(numbers));
This code defines a function expression that adds up all numbers in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each item in the array.
- How many times: Once for every element in the array.
As the array gets bigger, the function does more additions, one for each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Function expressions always run instantly, so time doesn't grow with input."
[OK] Correct: The way a function is written (expression or declaration) doesn't change how many steps it takes; what matters is what the function does inside.
Understanding how loops inside functions affect time helps you explain your code clearly and shows you know how to write efficient programs.
"What if we changed the for-loop to a nested loop inside the function? How would the time complexity change?"