JavaScript provides several built-in error types that describe different error situations:

  • SyntaxError: Thrown when there’s a syntax issue in the code, often due to misspelled keywords or missing parentheses.
  • ReferenceError: Occurs when code references a variable or function that hasn’t been declared.
  • TypeError: Thrown when an operation is performed on a variable of the wrong type (e.g., calling a function on a non-function).
JavaScript
try {
  eval("var a = ");  // Incomplete syntax
} catch (error) {
  console.log("Syntax Error:", error.message);
}

Output:

Syntax Error: Unexpected end of input

SyntaxError is caught when the code syntax is incorrect, such as missing values or parentheses.

JavaScript
try {
  console.log(nonExistentVariable);
} catch (error) {
  console.log("Reference Error:", error.message);
}

Output:

Reference Error: nonExistentVariable is not defined

ReferenceError occurs when trying to access a variable that hasn’t been defined.

JavaScript
try {
  let num = 5;
  num.toUpperCase();  // Number does not have a toUpperCase method
} catch (error) {
  console.log("Type Error:", error.message);
}

Output:

Type Error: num.toUpperCase is not a function

TypeError is thrown when trying to use a method or property on a data type that doesn’t support it, as in trying to call a string method on a number.