Welcome to our deep dive into the world of JavaScript (JS) Error Object! This tutorial is designed for both beginners and intermediates, so let's get started on this exciting journey. š
Error objects in JavaScript are special types of objects that contain information about errors or exceptions that occur during the execution of a script. They help developers understand and debug issues more efficiently.
// Creating an Error object
const myError = new Error("Custom Error");
console.log(myError);š” Pro Tip: Custom Error objects can be created to provide more specific information about an error.
JavaScript provides several built-in error types to handle different types of errors.
SyntaxError: Thrown when JavaScript encounters a syntax error, such as a missing bracket.
ReferenceError: Thrown when a variable or function is accessed before it has been declared or is not defined.
TypeError: Thrown when an operation or function is performed on a value of incorrect type.
RangeError: Thrown when a value is outside the valid range for a method or property.
Let's see some examples:
// Syntax Error
let x = 10
let y = 5
let z = x + y + // Syntax Error: Missing semicolon
// Reference Error
console.log(undeclaredVariable); // ReferenceError: undeclaredVariable is not defined
// TypeError
let str = "5";
let num = Number(str) + 1; // TypeError: Cannot convert a string to a number
// RangeError
let arr = new Array(5);
arr[6] = "Hello"; // RangeError: arr is 5 elements long, only arrays with a length of at least 6 can have property 6Errors can be handled using try-catch blocks. This allows us to catch errors and execute specific code to handle them, making our scripts more robust.
// Try-catch example
try {
let str = "5";
let num = Number(str) + 1;
} catch (error) {
console.log("An error occurred:", error);
}What is an Error object in JavaScript?
By the end of this tutorial, you should have a solid understanding of error objects in JavaScript, including built-in error types and how to handle errors using try-catch blocks. Happy coding! š¤š§š