Throwing errors in Javascript - Time & Space Complexity
When we throw errors in JavaScript, it's important to know how this affects the program's speed as it runs.
We want to see how the time to run changes when errors happen inside loops or repeated code.
Analyze the time complexity of the following code snippet.
function checkNumbers(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] < 0) {
throw new Error('Negative number found');
}
}
return true;
}
This code checks each number in an array and throws an error if it finds a negative number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element of the array.
- How many times: Up to the length of the array, once per element.
As the array gets bigger, the loop runs more times, checking each number until it finds a negative or finishes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows directly with the size of the array.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items checked.
[X] Wrong: "Throwing an error inside a loop makes the whole loop run slower every time."
[OK] Correct: The loop stops as soon as the error is thrown, so it doesn't always run through all items. The error itself doesn't slow down each check.
Understanding how throwing errors affects loops helps you explain how your code handles problems efficiently and when it stops work early.
"What if we changed the code to collect all negative numbers before throwing a single error? How would the time complexity change?"