Engineering Core
ISB Vietnam's skilled software engineers deliver high-quality applications, leveraging their extensive experience in developing financial tools, business management systems, medical technology, and mobile/web platforms.

When you write JavaScript, you'll run into errors. The trick is to know how to deal with them and use debugging tools to find out why they happen. This guide will help you grasp error handling, use good debugging methods, and show you some real examples.

I. Types of Errors in JavaScript

What is an error in JavaScript?

An error in JavaScript occurs when something goes wrong in the code, preventing it from executing as expected. Errors can be caused by a variety of issues, from syntax mistakes to unexpected values or incorrect logic. When an error occurs, JavaScript often halts the execution of the script and may display an error message to help identify the problem. JavaScript errors can disrupt the user experience if left unhandled, making it essential to detect and manage them effectively.

Common Types of Errors in JavaScript

1. Syntax Errors:

  • Happen when you write code that doesn't follow the rules, like forgetting parentheses or semicolons.
  • Example:
// Missing closing parenthesis
if (true { console.log("Hello"); }
  • The browser will show an error message like: "Unexpected token {".

2. ReferenceErrors:

  • A ReferenceError happens when the code tries to access a variable or function that hasn’t been defined.
  • Example:

console.log(myVariable); // myVariable has not been declared
  • The browser will show an error message like: "myVariable is not defined".

3. TypeErrors:

  • This error occurs when an operation is performed on a value of the wrong data type, such as calling a non-function as a function or accessing a property on undefined.
  • Example:
let num = 5;
num.toUpperCase(); // Error: toUpperCase is not a function on numbers
  • The browser will show an error message like: "myVariable is not defined".

4. RangeErrors:

  • RangeErrors occur when a value is outside the allowable range. Common examples include using an invalid array length or a number too large for a specific operation.
  • Example:
let arr = new Array(-1); // Negative array length is invalid
  • The browser will show an error message like: "Invalid array length".

5. EvalErrors:

  • These errors are thrown by the eval() function, which executes code as a string. Although rarely used, if eval() fails, it produces an EvalError.
  • Example:
eval("alert('Hello)"); // Missing a closing quote

6. URIErrors:

  • A URIError occurs when encodeURI(), decodeURI(), or similar functions are used incorrectly, such as passing an invalid URL format.
  • Example:
decodeURIComponent('%'); // % is incomplete encoding
  • The browser will show an error message like: "URI malformed".

7. InternalError:

  • An InternalError in JavaScript occurs when there is an issue within the JavaScript engine itself, often related to excessive resource consumption like memory or stack depth. This type of error is less common in typical JavaScript development but can occur in cases of infinite recursion, deep nesting, or excessive memory usage.
  • Example:
function recursiveFunction() {
    return recursiveFunction(); // Infinite recursion
}
try {
    recursiveFunction();
} catch (error) {
    console.error(error);
}
  • The browser will show an error message like: "Maximum call stack size exceede".

8. AggregateErrors (ES2021+):

  • An AggregateError is thrown when multiple errors are encountered simultaneously, such as in a Promise.any() operation. AggregateErrors contain a list of individual errors in their errors property.
  • Example:
const promises = [
    Promise.reject(new Error("Error 1")),
    Promise.reject(new Error("Error 2")),
    Promise.reject(new Error("Error 3"))
];

Promise.any(promises)
    .catch(aggregateError = {
        console.error("AggregateError:", aggregateError);
        aggregateError.errors.forEach((error, index) = {
            console.log(`Error ${index + 1}: ${error.message}`);
        });
    });}
  • Output:
AggregateError: All promises were rejected
    VM369:11 Error 1: Error 1
    VM369:11 Error 2: Error 2
    VM369:11 Error 3: Error 3

9. Logical Errors:

  • In addition to the JavaScript errors that are reported, there can also be logic errors that go undetected. While JavaScript errors usually stop the code from running correctly and display an error message, logic errors occur when the code runs without any visible issues but produces unintended or incorrect results. Identifying and fixing these logic errors requires a deeper understanding of how the code should behave, as they are often more subtle and challenging to diagnose.
  • Example:
function add(a, b) {
   return a - b; // This should be a + b
}
console.log(add(2, 3));// You'll get -1 instead of 5

II. Error Handling in JavaScript

1. Handling Errors Using try...catch

The try...catch statement in JavaScript is used to handle errors gracefully, allowing code execution to continue even if an error occurs. When an error is thrown within the try block, the control passes to the catch block, where the error can be managed without crashing the program.

a. Syntax:

try {
    // Code that might cause an error
} catch (error) {
    // Handle the error here
    console.error(error.message);
}

b. Example: Input Validation

function divide(a, b) {
    try {
        if (typeof a !== "number" || typeof b !== "number") {
            throw new TypeError("Inputs must be numbers"); // Throws a TypeError
        }
        if (b === 0) {
            throw new Error("Cannot divide by zero"); // Throws a custom error
        }
        return a / b;
    } catch (error) {
        console.error("Error:", error.message); // Handles any thrown error
    }
}
console.log(divide(10, 0)); // "Error: Cannot divide by zero"
console.log(divide(10, "two")); // "Error: Inputs must be numbers"

c. Benefits of Using try...catch

  • Prevents Program Crashes: Handles errors without stopping program execution.
  • Improves User Experience: Provides meaningful feedback instead of cryptic errors.
  • Custom Error Messages: Allows for custom messages to make debugging easier.

Using try...catch makes error handling straightforward and keeps the code resilient to unexpected issues, ensuring smoother operation and better debugging.

2. Using console.log() for Debugging

console.log() is a simple but super helpful tool to check variable values and execution steps.

Example:

function calculateArea(radius) {
    console.log("Radius received:", radius); // Check the value of 'radius'
    if (radius <= 0) {
        console.error("Radius must be greater than 0");
        return;
    }
    const area = Math.PI * radius * radius;
    console.log("Calculated area:" area); // Check the calculation result
    return area;
}

calculateArea(-5); // Logs an error because 'radius' is less than 0
  • Explanation:console.log() helps us see values at each step to find problems.

3. Using debugger to Pause Code Execution

The debugger statement has an influence on JavaScript execution by pausing it at the exact spot you choose. This allows you to check variables and see how your program is doing at that moment.

Example:

function findMax(arr) {
    debugger; // Pauses here
    let max = arr[0];
    for (let i = 1; i < arr.length; i++) {
        if (arr[i]  max) {
            max = arr[i];
        }
    }
    return max;
}

findMax([3 1 4 1 5 9]);
  • Explanation:If you run this code in a browser with DevTools open, JavaScript will pause at debugger, allowing you to inspect arr, max, and other values during the loop.

4. Debugging Tools in Chrome DevTools

Chrome DevTools offers a robust set of tools to debug JavaScript such as:

  • Console: To see logs, warnings, and errors.
  • Sources Tab: To set breakpoints and check variable values.
  • Network Tab: To monitor API requests and responses.

Practical Example:

1. Start by visiting a webpage that has the JavaScript code you want to check out.

2. Hit F12 or Ctrl + Shift + I (on Windows) to open DevTools.

3. Head to the Sources section and put a breakpoint where you need it.

4. Reload the page and observe variable states when the program pauses.

Conclusion

Debugging and error handling are essential skills that help JavaScript developers write code more effectively. Mastering tools like try...catch, console.log(), debugger, and Chrome DevTools will enable you to find errors quickly and improve your productivity.

Written by
Author Avatar
Engineering Core
ISB Vietnam's skilled software engineers deliver high-quality applications, leveraging their extensive experience in developing financial tools, business management systems, medical technology, and mobile/web platforms.

COMPANY PROFILE

Please check out our Company Profile.

Download

COMPANY PORTFOLIO

Explore my work!

Download

ASK ISB Vietnam ABOUT DEVELOPMENT

Let's talk about your project!

Contact US