Type Error Vs. Reference Error...

Type Error Vs. Reference Error...

Table of contents

If you write code in javascript and you also saw some errors. In the bunch of error types, today we talked about type errors and reference errors.

TYPE ERROR

A type error in javascript occurs when the variable exists but you try to perform an inappropriate operation such as if you using an integer type variable and you want to reassign the value of the type string then it throws a type error. let's take an example of this,

let a = 1;
a = "hello"; // Shows an type error

In the above example, you see that when we declare variable a and assign an integer number. So for a javascript compiler variable, a is an integer but after the declaration, we reassign a string to a integer variable. This makes no sense. That's why the javascript compiler throws a TypeError.

REFERENCE ERROR

Reference error in javascript takes place when we use a variable that is not available in the code or we can also say that reference error occurs when we try to use a variable that is not declared before its use. This could happen if you mistype the name of a variable or if you try to access the variable that has already been garbage collected. This could also happen when you declare a variable inside the scope and want to access it outside the scope.

Here are the examples of reference error

console.log(a); // Reference Error
const a = 10;
const xy = () =>{
    const a2 = 10;
}
console.log(a2);  // Reference Error

In the above code, the first console log gives an error because variable a is not declared before it had been used and in the second console log variable a2 is declared inside a scope so it is accessible only inside its scope not outside of the scope. So that's why it gives a Reference error.

In summary, a type error is related to data types and operations, while a reference error is related to variables and their scope.