What are Reference Errors and Type Errors in Javascript?

What are Reference Errors and Type Errors in Javascript?

When you are learning javascript there is a lot of errors that you can face, but the most common mistakes are reference and type errors. What is a reference or type error? Let's see.

Reference Error:

If you visit the MDN document for this error you will see this explanation or definition :

The ReferenceError an object represents an error when a variable that doesn't exist (or hasn't yet been initialized) in the current scope is referenced.

What does this mean let's try to understand by some of the examples,

console.log(a)
const a = 5;

//output: Reference Error

  • In the first line, you are consoling a but the variable is not yet defined. Try why the console is throwing a reference error.

  • It's like finding a person's address, but the person hasn't even bought the land.

How to solve this error?

  • When you are writing your code, always declare all variables on top(even in function).
//solution:
const a = 5;
console.log(a); 
//output: 5;

What if you are accessing the value which is declared inside a function?


function add(){
    let a = 5;
    let b = 6;
    return a+b;
}

console.log(a);
//What will be output?

  • Here also you will have a reference error because you are accessing a which is declared inside the function.

  • What to do in this situation? Just declared the variables outside the function if you are planning to access those variables outside of that function.

//solution
let a = 5;
let b = 6;
function add(){
    return a+b;
}

console.log(add(), a);

//output: 11, 5;

Reference error will also show if you are redeclaring the value.

function value(){
    let number = 1;
    if(true){
        number++;
    }
    return number;
}

console.log(value());

//output: 2;

//Reference Error will show if redeclared "number". 
if(true){
    let number = number + 1;
}

Type Error:

You will get this error if you're using anything that is not intended to use in that way. Like you are making tea inside a microwave.

const a = 6;
console.log(a());

You can clearly see that it is showing that a is not a function. a is a variable that has a value of 6.

Solution:

const a = 6;
console.log(a);

Let's see another example:

const b = 6;
b = 7;

In this case, the const value has been changed but you can't do that. To change the variables you should use let .

Solution:

let b = 6;
b = 7;

//Output: 7;

TL;DR:

  • Reference Error will show if you are accessing the value outside the function or if the value has not been defined.

  • Type error will show if you are using anything that shouldn't be used in that way, like accessing a function with the same name, but that has been declared as a variable.