Open In App

How to prevent TypeError in Node.js ?

In this article we are going to learn about that how can we prevent the code from crashing if in case there is any kind of TypeError and how to handle them in node.js.

There are various Reasons for TypeError:



Calling a value as a function: Suppose there is a variable named num and we have stored the value 8 in it and we are calling the num variable as a function while it is not a function but it is just a variable that is a container of a value then there you will receive a TypeError with name num is not a function.

Example: Let’s understand with the help of an example of the error we will be receiving:




let num = 7;
num();
  
let string = "My name is Prince Kumar";
string();

Output:



TypeError: num is not a function

Calling an object as a function: Suppose we have declared an empty object having named obj and we are trying to call it as a function then there will be receiving a TypeError with the name Obj is not a function.

Example: Let’s understand with help of an example of the error we will be receiving:




// We have defined an empty object with name obj
let obj = {};
obj();

Output:

TypeError: obj is not a function

Iterating a number using a conditional loop: Suppose we have declared a variable with a named number and we are trying to iterate the integer number then there will be receiving a TypeError with the name number is not iterable.

Example: Let’s understand with help of an example of the error we will be receiving:




let number = 1234679;
for(value of number){
    console.log(value);
}

Output:

TypeError: number is not iterable

Method to prevent from TypeError:

1. By using the try-catch method: Try-catch method help us to detect the name of the TypeError and the reason why this TypeError is given by node.js.

Syntax:

try{
    // set of statements
} catch(e){
    // print e.name means it will tell you the name of error
    // print e.message it will give you the description about the error
}

Example: Let’s see the implementation as explained below:




try{
    let num = 7;
    num();
} catch(e){
    console.log("Name of Error: ",e.name);
    console.log("Description about Error: ", e.message);
}

Output:

Name of Error:  TypeError
Description about Error:  num is not a function

Article Tags :