Reference Error Vs Type Error in Javascript

Reference Error Vs Type Error in Javascript

In Javascript we will be seeing a lot of errors while coding, so today we will be discussing the two most occurring errors i.e Reference error and Type error.

What is a Reference Error?

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

When any value is assigned to an undeclared variable or an assignment without the var keyword or variable is not in your current scope, it might lead to unexpected results and that’s why JavaScript presents an ReferenceError: assignment to undeclared variable "x" in strict mode. And this error causes a problem in the execution of functions.

function logName(){
     console.log(name);
     name = 'Akash';
}
logName(); //It will throw an reference error saying name is not declared
if(true){
    let a = 1
}
console.log(a)
//output ReferenceError: a is not defined

So as we know that when we are trying to access a name variable before declaring or initializing it so hence it's throwing a reference error that name is not declared.

How to avoid getting a reference error

The easiest way to avoid getting reference errors is to refer to or access only defined variables. Only use variables that exist.

You can also use conditional statements and error handling to avoid running code if a variable or a function does not exist.

What is a Type Error?

The TypeError object represents an error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type.

A TypeError may be thrown when:

  • an operand or argument passed to a function is incompatible with the type expected by that operator or function; or

  • when attempting to modify a value that cannot be changed; or

  • when attempting to use a value in an inappropriate way.

let val = null;
console.log(val.bar);//Uncaught TypeError: cannot read property ‘bar’ of null
val.name = "Akash";//Uncaught TypeError: cannot set property ‘namee’ of undefined

const a = 1
a = 2 // you reassign a const type variable again
//output TypeError: Assignment to constant variable

How to avoid getting a type error

The easiest way to prevent type errors is to avoid using the same names for different variables and functions.

If you use different names, you will not get confused or replace one with another, and you can easily avoid getting this error.

Another way is to make sure you use variables as they're intended to be used. Instead of using const when you need to reassign a value, use let (which allows this kind of change).

Conclusion

It's good to know commonly occurring errors and how to avoid them. Now we know and we can easily debug your code when you already know how to resolve your errors. so if we see anytimeRefrenceError or TypeError, the reason behind it is so we can easily debug.