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?"
Practice
throw statement do in JavaScript?Solution
Step 1: Understand the purpose of
Thethrowthrowstatement is used to create an error and stop normal program execution.Step 2: Differentiate from error handling
Unliketry...catchwhich handles errors,throwactually creates the error.Final Answer:
Stops the program and creates an error. -> Option AQuick Check:
throwcreates error = A [OK]
- Confusing throw with try...catch
- Thinking throw handles errors
- Believing throw declares variables
Solution
Step 1: Recall the correct Error constructor usage
In JavaScript, to create an error object, usenew Error('message').Step 2: Check syntax correctness
Only throw new Error('Invalid input'); usesthrow new Error('Invalid input');which is correct syntax.Final Answer:
throw new Error('Invalid input'); -> Option CQuick Check:
Correct syntax usesnew Error= C [OK]
- Missing 'new' keyword
- Using lowercase 'error' instead of 'Error'
- Omitting parentheses
try {
throw new Error('Oops!');
} catch (e) {
console.log(e.message);
}Solution
Step 1: Understand the throw and catch behavior
The code throws an error with message 'Oops!'. The catch block catches it and logse.message.Step 2: Determine what
e.messagecontainse.messageis the string 'Oops!'. Soconsole.log(e.message)prints 'Oops!'.Final Answer:
Oops! -> Option AQuick Check:
Logging error message prints 'Oops!' = A [OK]
- Printing whole error object instead of message
- Expecting 'Error: Oops!' instead of just message
- Thinking no output occurs
try {
throw new Error('Fail');
} catch e {
console.log(e.message);
}Solution
Step 1: Check catch syntax
In JavaScript, the catch block must have parentheses around the error parameter, likecatch (e).Step 2: Identify the syntax error
The code usescatch ewithout parentheses, which causes a syntax error.Final Answer:
Missing parentheses around catch parameter. -> Option DQuick Check:
Catch parameter needs parentheses = B [OK]
- Omitting parentheses in catch
- Misplacing throw statement
- Confusing error message with syntax error
Solution
Step 1: Understand falsy values for empty or null input
In JavaScript,!inputis true if input is null, undefined, empty string, 0, or false.Step 2: Check which option correctly throws error for empty or null
if (!input) throw new Error('Input required'); usesif (!input) throw new Error('Input required');which covers empty string and null correctly with proper syntax.Final Answer:
if (!input) throw new Error('Input required'); -> Option BQuick Check:
Use !input to check empty/null and throw Error = D [OK]
- Using lowercase 'error' instead of 'Error'
- Throwing error only for empty string but missing null
- Throwing error when input is valid
Ready to prove it?
Pass the test and this pattern moves unknown
