JS Errors
JS Errors
Errors occur when JavaScript encounters a problem it cannot execute. Understanding errors helps you write safer and more predictable code.
JS Errors Intro
JavaScript has runtime errors and syntax errors.
// Syntax error (code will not run) // let x = ; let a = 10; console.log(a.toUpperCase()); // TypeError at runtime
Syntax errors stop execution immediately. Runtime errors occur while the program is running.
JS Errors Silent
Some operations do not throw errors but return unexpected results. These are called silent failures.
let result = "5" - 2; console.log(result); // 3 (implicit conversion)
Accessing undefined properties does not throw an error:
const user = {};
console.log(user.address); // undefined
Optional chaining prevents crashes when accessing nested properties:
console.log(user.address?.city); // undefined instead of error
JS Error Statements
Use try...catch to handle errors gracefully.
try {
let x = y; // y is not defined
} catch (error) {
console.log("An error occurred:", error.message);
} finally {
console.log("Done");
}
Use throw to create custom errors.
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero");
}
return a / b;
}
try {
divide(10, 0);
} catch (e) {
console.log(e.message);
}
JS Error Object
The Error object contains useful properties like name and message.
try {
undefinedFunction();
} catch (e) {
console.log(e.name); // ReferenceError
console.log(e.message);
console.log(e.stack);
}
Common built-in error types:
- SyntaxError
- ReferenceError
- TypeError
- RangeError
- URIError
Custom Error Classes
You can create your own error types.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
throw new ValidationError("Invalid input");
Strict Mode and Errors
Strict mode prevents silent errors and makes debugging easier.
"use strict"; x = 10; // ReferenceError (no accidental globals)
Best Practice
Use try/catch around code that may fail (network calls, JSON parsing, user input). Always throw meaningful errors instead of silent failures.
Next Step
Continue with JS Debugging to learn how to inspect and fix issues efficiently.