Error Types

In JavaScript, errors are objects that describe problems in code execution. Recognizing different error types helps in debugging and writing robust code.

Common JavaScript Error Types
Error TypeDescription
SyntaxErrorOccurs when code violates JavaScript syntax rules, e.g., missing brackets or unexpected tokens.
ReferenceErrorThrown when accessing a variable that is not declared or out of scope.
TypeErrorRaised when a value is not of the expected type or an operation is performed on an incompatible type.
RangeErrorOccurs when a numeric value is outside an allowable range, such as an invalid array length.
URIErrorThrown when global URI handling functions receive malformed parameters.
EvalErrorRelates to the eval() function misuse; rarely used in modern JavaScript.
Illustration of error_types
Illustration of error_types

💡 Key Insight

Understanding the error type helps pinpoint the root cause quickly — whether it’s a typo (SyntaxError), missing variable (ReferenceError), or wrong data usage (TypeError).

Below are concise examples demonstrating when each error type might occur:

📌 Deep Dive: Examples of Common Errors

JAVASCRIPT
// SyntaxError: missing closing parenthesis
if (true {
  console.log('Oops!');
}

// ReferenceError: x is not defined
console.log(x);

// TypeError: undefined is not a function
let num = 5;
num.toUpperCase();

// RangeError: invalid array length
let arr = new Array(-1);

// URIError: malformed URI sequence
decodeURIComponent('%');

// EvalError: deprecated usage (rare)
eval('var a = 1;');
Output
SyntaxError, ReferenceError, TypeError, RangeError, URIError, EvalError thrown respectively

⚠️ Handling Errors

Most errors can be caught using try...catch blocks to prevent script termination and provide graceful recovery.

Errors inherit from the built-in Error object, which holds properties like message and stack useful for debugging.

💡 Summary

  • SyntaxError: Code structure issues.
  • ReferenceError: Using undeclared variables.
  • TypeError: Invalid operations on data types.
  • RangeError: Values out of allowed range.
  • URIError: Problems with URI functions.
  • EvalError: Issues with eval() (rare).