Types of Errors in Javascript

Types of Errors in Javascript

There are several different types of javascript errors, so today we'll learn about a few of them.

Reference Error

We got a reference error when a variable is not initialized or doesn't exist in the current scope

Let's take some examples to understand better

We are accessing myVariable in the above example without initializing it.

In the above example, we are accessing without defining that's why we are getting a reference error.

Ways to Avoid Reference Error

  1. Always make sure to declare and define variables and functions before using them.

  2. To prevent situations where values are undefined and null, use error handling.

  3. Try to use strict mode.

Type Error

When we perform an operation on a value that is not the expected type in that case, a type error will occur.

Reasons for Type Error

  1. When we use an incorrect data type

  2. Type error occurs when we try to access properties of null or undefined values.

  3. Type Errors may occur when we use incorrect operators.

Examples of Type Error

In the above example, we are using string methods on an integer value.

In the above example, x is a string and y is an integer. When we perform addition operation with a string and a number, JavaScript converts the number to a string and concatenates the two values. But when we use the subtraction operator with a string and a number, JavaScript tries to convert the string to a number, but since it's not a valid number, it returns NaN (Not a Number).

Ways to Avoid Type Error

  1. Use strict equality (===) instead of loose equality (==): When comparing values, use the strict equality operator (===) instead of the loose equality operator (==).

  2. Before using variables check if it's not null or undefined. We can check using typeOf operator.