Reference Error & Type Error

Reference Error & Type Error

What are errors?

While executing a piece of code, the compiler may encounter an error that causes it to pause/stop the execution. In order to rectify and resolve the errors for successful execution, it is necessary for the developers to understand what the error means.

In this blog, we will be seeing the two most encountered runtime errors in JavaScript:

  1. Reference Error.

  2. Type Error.

Reference Error:

If you try to use a variable that you haven't created, a ReferenceError is thrown.

This type of error is thrown in the following scenarios:

  • When the variable is not declared. i.e, the variable we are trying to access doesn't exist in our program.
const name = "Vijayalakshmi";
const age = 20;
console.log(place) //We are trying to access a variable that is not declared. So Reference error is thrown

To resolve this error, we must declare the variables first and access it.

const name = "Vijayalakshmi";
const age = 20;
const place = "Tamil Nadu";
console.log(place)
  • Trying to access a variable before its declaration
const name = "Vijayalakshmi";
const age = 20;
console.log(place)
const place = "Tamil Nadu"; //We are trying to access a variable before its declared. So Reference error is thrown

To prevent this error, we must declare all the variables that we would use/access at the beginning of its scope.

const name = "Vijayalakshmi";
const age = 20;
const place = "Tamil Nadu";
console.log(place)
  • Trying to access a variable outside of its scope.
const a = 20;
const b = 10;
if( a !=0 && b!=0){
    const divide = a/b;
}
console.log(divide); //we are trying to access the "divide" variable outside of its scope (if block). Hence, Reference error is thrown

To resolve this error, we must access the variable within its scope.

const a = 20;
const b = 10;
if( a !=0 && b!=0){
    const divide = a/b;
    console.log(divide); 
}

TypeError:

This type of error occurs when an operation can not be performed. i.e., when we use a value that doesn't match the type of data that our code expects, a TypeError is thrown.

Below are the scenarios in which we may encounter TypeErrors:

  • when trying to modify a value that cannot be changed.
const sum = 0;
let num = 1;

while(num<=5){
    sum += num; //const value cannot be changed. TypeError is thrown
    num++;
}
  • when trying to operate on a value in an invalid manner
const name = "Viji";
console.log(name()); //inappropriate use of variable. TypeError is thrown

Hope this blog gives a clear understanding of what ReferenceErrors and TypeErrors are, when they might occur, and how to resolve them. Thank you.