Errors & Debugging
Errors & Debugging: TypeError → Fix with Optional Chaining Errors are not scary! Think of a red error message as a warning light on a car's dashboard: the light is not the fault,
TypeError → Fix with Optional Chaining
Errors are not scary! Think of a red error message as a warning light on a car's dashboard: the light is not the fault, it is the thing telling you where to look under the bonnet. `TypeError: Cannot read property 'text' of null` does not say "your code is broken"; it says "the element you asked for was not on the page". So if the message is this helpful, why do so many people wrap the error in `try-catch` and move on? Because silencing a failure is cheaper than solving it — in the short term. In tests the price is steep: an empty `catch` block turns a test that SHOULD fail into a green one. You already know why `catch (Exception e) {}` is frowned upon in Java; the same rule holds in JavaScript, plus an async trap on top — `try-catch` cannot catch anything thrown by an async function you called without `await`, and the error vanishes silently. The QA rule is blunt: catch an error only when you know what to do about it; otherwise let it explode. An exploding test is far cheaper than a quietly passing one. Let's learn the most common JavaScript errors and how to handle them using `try-catch` blocks.
Occurs when trying to reassign a value to a variable declared with const.
If the value needs to change over time, declare the variable with let instead.
Thrown when accessing a variable that has not been declared or is out of scope.
Check the variable name spelling or verify it was declared using let/const.
Occurs when invoking a method on an undefined object (similar to Java's NullPointerException).
Verify that the locator matches an active element and that proper waits are used before action.
Thrown when JSON.parse() encounters HTML content. The API returned a 404 page or error HTML instead of a proper JSON response.
Check `response.ok` before parsing. Validate the `Content-Type: application/json` header before calling JSON.parse().
Thrown when a non-function value (number, string, undefined) is invoked with parentheses as if it were a function.
Add `typeof myFn === 'function'` guard before the call, or verify the variable name is correctly spelled.
Thrown when infinite recursion overflows the call stack. Equivalent to Java's StackOverflowError.
Add a proper base case to the recursive function, or convert the recursion to an iterative loop.