Why conditional logic is needed in Javascript - Performance Analysis
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?
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.
- 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.
As the array gets bigger, the number of checks can grow, but sometimes it stops early.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Between 1 and 10 checks |
| 100 | Between 1 and 100 checks |
| 1000 | Between 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.
Time Complexity: O(n)
This means the time to finish grows roughly in step with the number of items to check.
[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.
Understanding how choices in code affect speed helps you explain your thinking clearly and write efficient programs.
"What if we changed the condition to check every item without stopping early? How would the time complexity change?"