DEV Community

Gurnav224
Gurnav224

Posted on

# What Are the Different Types of Errors in JavaScript?

In JavaScript, errors are inevitable parts of programming. They act as helpful messages that let us know when something has gone wrong. JavaScript provides a built-in Error object that contains valuable information about the error. Understanding the types of errors and their causes is crucial for debugging and writing robust code.

Let’s explore some of the most common types of errors in JavaScript: Syntax Error, Reference Error, and Type Error.


1. Syntax Error

A Syntax Error occurs when we write code that does not follow the correct syntax rules.

Example:

console.log('hello world'
Enter fullscreen mode Exit fullscreen mode

Reason: There’s a missing closing parenthesis. The JavaScript engine cannot parse this code.

  1. Reference Error A Reference Error occurs when we try to access a variable or function that has not been defined.

Example:

console.log(a);
Enter fullscreen mode Exit fullscreen mode

Reason: The variable a is not declared.

  1. Type Error A Type Error occurs when a value is used in an unexpected way or is of an unexpected type.

Here are a few common reasons why Type Errors occur:

  1. Calling a non-function If we try to invoke a variable as a function, but it is not actually a function, a Type Error will be thrown.

Example:


const obj = {};
obj();
// TypeError: obj is not a function
Enter fullscreen mode Exit fullscreen mode
  1. Accessing properties of undefined or null This error occurs when we try to access a property of a variable that is undefined or null.

Example:


let myVar;
console.log(myVar.name); 
// TypeError: Cannot read property 'name' of undefined
Enter fullscreen mode Exit fullscreen mode
  1. Modifying a constant variable A Type Error also occurs when we try to change a constant variable’s value.

Example:

const x = 5;
x = 10;
// TypeError: Assignment to constant variable
Enter fullscreen mode Exit fullscreen mode

Top comments (0)