0
0
Javascriptprogramming~5 mins

Function expression in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Function expression
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the array gets bigger, the function does more additions, one for each number.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the number of items; double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the input size.

Common Mistake

[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.

Interview Connect

Understanding how loops inside functions affect time helps you explain your code clearly and shows you know how to write efficient programs.

Self-Check

"What if we changed the for-loop to a nested loop inside the function? How would the time complexity change?"