Clarity On TypeError And RefrenceError

Debashis KarDebashis Kar
2 min read
  1. TypeError

  2. RefrenceError

  3. Conclusion

TypeError:

TypeError occurs when a value is not of an expected type. In simple words, TypeError occurs when an argument or value passed is not the expected type that can be operated to produce any output.

Examples:

Let's understand TypeError with examples.

Ex 1:-

const a= 10;
a() //TypeError occurs

Here TypeError occurs because we are trying to run a function with then function name "a" but a is not defined as a function above.

Ex 2:-

const a= 11;
const b= "11";
const c= a+b //TypeError occurs

Here the type of variable a is "Number" and b is "String". so we can't sum a String to a Number because of type is not the same. So TypeError occurs.

Ex 3:-

const obj={};
 obj[0];// TypeError occurs

Here we know that objects have no index number. So trying to access index of an object like an array will throw a TypeError.

Ex 4:-

const a="I am Dev";
const b= Number(a) // TypeError Occurs

Here variable a is a "String" and a "Paragraph". So trying to convert a String to a Number is impossible. So TypeError occurs here.

RefrenceError:

RefrenceError occurs when you try to access a variable or try to do some operation with a variable which is not yet declared . It also occurs when you try to access a variable which is in different scope.

Examples:

Let's understand it with examples.

Ex 1:-

const a= 1 ;
const b= a+c // RefrenceError occurs

Here RefrenceError occurs because we are trying to add the value of variable c to the value of variable a despite having no variable c.

Ex 2:-

Function print(){
console.log("Hello World")
}
pint(); // RefrenceError occurs

RefrenceError will occur here because we spell it wrong as "pint" instead of "print" while calling the function.

ex 3:-

Function app(){
const a= 10;
}
console.log(a) //RefrenceError occurs

Here RefrenceError will occur because we are trying to access the value of the variable a from outside of the function or block.

Conclusion:

Better understanding and having maximum clarity of types of errors will make us better programmers because when we understand why and how a specific type of error occurs we can fix it in less time and with less hassle.

0
Subscribe to my newsletter

Read articles from Debashis Kar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Debashis Kar
Debashis Kar