JavaScript Errors

In JavaScript, errors are runtime issues that occur during the execution of a script. These errors can halt the execution of the program if not handled properly. JavaScript provides various error types to help developers identify and troubleshoot issues effectively.

Types of JavaScript Errors

  1. Syntax Errors: Occur when the code violates the syntax rules of JavaScript.
  2. Reference Errors: Occur when a non-existent variable is referenced.
  3. Type Errors: Occur when an operation is performed on a value of the wrong type.
  4. Range Errors: Occur when a value is not within the set or allowed range.
  5. Eval Errors: Occur due to incorrect usage of the eval() function.
  6. URI Errors: Occur when encodeURI() or decodeURI() functions are misused.

1. Syntax Errors

A syntax error occurs when the JavaScript engine encounters tokens or code that do not conform to the syntax rules.

try {
    eval('alert("Hello);');  // Missing closing quotation mark
} catch (error) {
    console.log("Syntax Error: " + error.message);
}

Try It Now

2. Reference Errors

A reference error occurs when trying to access a variable that is not defined.

try {
    console.log(x);  // x is not defined
} catch (error) {
    console.log("Reference Error: " + error.message);
}

Try It Now

3. Type Errors

A type error occurs when a value is not of the expected type.

try {
    let num = 5;
    num.toUpperCase();  // toUpperCase() is not a function for numbers
} catch (error) {
    console.log("Type Error: " + error.message);
}

Try It Now

4. Range Errors

A range error occurs when a number is outside its allowed range.

try {
    let num = 1;
    num.toPrecision(500);  // Precision is out of range
} catch (error) {
    console.log("Range Error: " + error.message);
}

Try It Now

5. Eval Errors

Eval errors occur when there is an issue with the eval() function. Although eval() errors are rare, they can still happen.

try {
    eval("alert('Hello)");  // Syntax error inside eval
} catch (error) {
    console.log("Eval Error: " + error.message);
}

Try It Now

6. URI Errors

URI errors occur when using malformed URIs in functions such as decodeURI() or encodeURI().

try {
    decodeURI("%");  // Invalid URI component
} catch (error) {
    console.log("URI Error: " + error.message);
}

Try It Now

Custom Error Messages

You can throw custom errors using the throw statement to provide more meaningful error messages.

try {
    let age = -5;
    if (age < 0) throw "Age cannot be negative";
} catch (error) {
    console.log("Custom Error: " + error);
}

Try It Now

Conclusion

JavaScript provides a robust error handling mechanism to catch and manage errors effectively. By understanding the different types of errors and how to handle them, you can make your code more reliable and user-friendly.