DEV Community

Cover image for 😵‍💫 Understanding and Handling Common JavaScript Errors
Artem Turlenko
Artem Turlenko

Posted on

😵‍💫 Understanding and Handling Common JavaScript Errors

JavaScript errors are inevitable, but knowing how to recognize, understand, and handle them effectively can significantly reduce your debugging time. In this post, we'll explore common JavaScript errors including TypeError, ReferenceError, RangeError, URIError, AggregateError, EvalError, InternalError, and SyntaxError, and discuss how to handle them gracefully.


1. TypeError

A TypeError occurs when a variable or parameter is not of a valid type.

Common Causes:

  • Trying to invoke methods on undefined or null.
  • Passing incorrect data types to functions.

Example:

const num = 5;
num.toUpperCase(); // TypeError: num.toUpperCase is not a function
Enter fullscreen mode Exit fullscreen mode

2. ReferenceError

A ReferenceError occurs when referencing a variable that is not defined or out of scope.

Common Causes:

  • Using undeclared variables.
  • Accessing variables out of their defined scope.

Example:

console.log(myVar); // ReferenceError: myVar is not defined
Enter fullscreen mode Exit fullscreen mode

3. RangeError

A RangeError occurs when a number is outside of an allowable range.

Common Causes:

  • Creating arrays with invalid lengths.
  • Stack overflow from excessive recursion.

Example:

const arr = new Array(-1); // RangeError: Invalid array length
Enter fullscreen mode Exit fullscreen mode

4. URIError

A URIError occurs from incorrect use of URI functions like decodeURIComponent() or encodeURIComponent().

Common Causes:

  • Malformed URI sequences.

Example:

decodeURIComponent('%'); // URIError: URI malformed
Enter fullscreen mode Exit fullscreen mode

5. AggregateError

An AggregateError represents multiple errors wrapped into one, typically when handling promises.

Common Causes:

  • When multiple promises are rejected.

Example:

Promise.any([
  Promise.reject('Error 1'),
  Promise.reject('Error 2')
]).catch(e => console.log(e)); // AggregateError
Enter fullscreen mode Exit fullscreen mode

6. EvalError

An EvalError historically indicated errors related to the eval() function (rare in modern JavaScript).

Common Causes:

  • Incorrect use of eval().

Example (obsolete):

try {
  eval('alert("Hello");');
} catch (e) {
  if (e instanceof EvalError) {
    console.error(e);
  }
}
Enter fullscreen mode Exit fullscreen mode

7. InternalError

An InternalError indicates an internal JavaScript engine error, often due to excessive recursion (mostly seen in Firefox).

Common Causes:

  • Infinite recursion loops.

Example:

function recurse() {
  recurse();
}
recurse(); // InternalError: too much recursion
Enter fullscreen mode Exit fullscreen mode

8. SyntaxError

A SyntaxError occurs due to incorrect syntax in your code.

Common Causes:

  • Missing brackets, parentheses, or semicolons.

Example:

if (true { // SyntaxError: Unexpected token '{'
  console.log("Hello");
}
Enter fullscreen mode Exit fullscreen mode

How to Handle JavaScript Errors

1. Try/Catch Blocks

Gracefully handle exceptions:

try {
  riskyFunction();
} catch (error) {
  console.error('An error occurred:', error);
}
Enter fullscreen mode Exit fullscreen mode

2. Error Logging

Log errors to an external monitoring service:

catch (error) {
  logErrorToService(error);
}
Enter fullscreen mode Exit fullscreen mode

3. Input Validation

Check variables and function parameters before use:

if (typeof input === 'string') {
  process(input);
} else {
  console.warn('Invalid input type');
}
Enter fullscreen mode Exit fullscreen mode

4. ESLint or TypeScript

Tools like ESLint or TypeScript can detect potential errors during development, reducing runtime errors.


Conclusion

Understanding and effectively handling JavaScript errors greatly improves your coding workflow and helps ensure reliable, robust applications.

What is the trickiest JavaScript error you've encountered? Let's discuss in the comments below! 🚀

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

If this article connected with you, consider tapping ❤️ or leaving a brief comment to share your thoughts!

Okay