Try-Catch Blocks

The try...catch statement is used to handle exceptions and prevent your code from crashing when an error occurs. The code that might throw an exception is wrapped in the try block, and the catch block is executed if an exception is thrown.

try {
// Code that might throw an exception
const result = someFunction();
console.log(result);
} catch (error) {
// Handle the exception
console.error("An error occurred:", error);
}

Error Objects

When an exception is thrown, an Error object is created, which contains information about the error, such as the error message and the call stack. You can access these properties to provide more meaningful error messages or log the errors for debugging purposes.

try {
throw new Error("Something went wrong");
} catch (error) {
console.error(error.name); // "Error"
console.error(error.message); // "Something went wrong"
console.error(error.stack); // Callstack with line numbers
}

Debugging Techniques

Debugging is the process of identifying and fixing errors or issues in your code. JavaScript provides several debugging tools and techniques to help you with this process:

Console

The browser's console is a powerful debugging tool that allows you to log messages, view variable values, and interact with the DOM. You can use the console.log() method to print messages to the console, or use other methods like console.error(), console.warn(), and console.table().

const user = { name: "John", age: 30 };
console.log("User object:", user);
console.table(user); // Displays the object in a tabular format

Breakpoints

Breakpoints allow you to pause the execution of your code at a specific line, so you can inspect variables and step through the code line by line. You can set breakpoints in your code using the browser's developer tools or by using the debugger; statement.

function multiply(a, b) {
debugger; // Set a breakpoint here
return a * b;
}

Other Debugging Tools

Modern browsers and IDEs (Integrated Development Environments) provide additional debugging tools and features, such as source maps, code linters, and profiling tools. These tools can help you catch errors, maintain code quality, and optimize performance.

In the next chapter, we'll explore modules and some of the newer features introduced in ECMAScript 6 (ES6) and beyond.