Js Errors in JavaScript
? JavaScript Errors
JavaScript errors occur when the code cannot execute properly. Understanding error types helps you debug effectively.
1. Common Error Types
| Error Type | Description | Example |
|---|---|---|
| SyntaxError | Code violates JavaScript syntax rules | eval('foo bar') |
| ReferenceError | Accessing a variable that does not exist | console.log(x) when x undefined |
| TypeError | Operation on a value of the wrong type | null.foo() |
| RangeError | Value is out of allowed range | new Array(-1) |
| URIError | Malformed URI in encode/decode functions | decodeURIComponent('%') |
| EvalError | Error related to eval() function | Rarely used |
2. Handling Errors: try...catch
try { // Code that might throw JSON.parse("invalid json");} catch (error) { console.error("Caught an error:", error.name, error.message);}3. Throwing Custom Errors
function checkAge(age) { if (age < 18) { throw new Error("Too young!"); } return "Access granted";}try { checkAge(15);} catch (e) { console.error(e.message); // "Too young!"}4. Error Object Properties
name— Error type (e.g., "ReferenceError")message— Description of the errorstack— Stack trace (helps debug)
5. Debugging Tips
Use browser console or Node.js terminal to view error messages.
Check stack trace to locate the error source.
Use
console.error()to log errors.
Want examples of asynchronous error handling or custom error classes?