0
0
Javascriptprogramming~5 mins

Why conditional logic is needed in Javascript - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why conditional logic is needed
O(n)
Understanding Time Complexity

We want to see how adding choices in code affects how long it takes to run.

How does the program's work change when it decides between options?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function checkNumber(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > 10) {
      return true;
    }
  }
  return false;
}
    

This code looks through an array and stops as soon as it finds a number bigger than 10.

Identify Repeating Operations
  • Primary operation: Looping through the array elements one by one.
  • How many times: Up to the length of the array, but may stop early if condition is met.
How Execution Grows With Input

As the array gets bigger, the number of checks can grow, but sometimes it stops early.

Input Size (n)Approx. Operations
10Between 1 and 10 checks
100Between 1 and 100 checks
1000Between 1 and 1000 checks

Pattern observation: The work can be less if the condition is met early, but in the worst case it grows with the array size.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows roughly in step with the number of items to check.

Common Mistake

[X] Wrong: "Because the loop can stop early, the time is always small and constant."

[OK] Correct: Sometimes the condition is never met, so the loop checks every item, making time grow with input size.

Interview Connect

Understanding how choices in code affect speed helps you explain your thinking clearly and write efficient programs.

Self-Check

"What if we changed the condition to check every item without stopping early? How would the time complexity change?"