We face a hell lot of errors while writing Javascript code. What if we know all types of errors that might occur in Javascript, It would be much easier for us to debug by seeing the error type. Here, we’ll talk about two much-faced errors: ReferenceError & TypeError.ReferenceError
Let’s take an example, what if you try to find something in your room that doesn’t even exist there? Similarily when you try to access a variable that doesn’t exist or hasn’t yet been initialized in the current scope, then the compiler will throw a ReferenceError.
function example1() {
const a = 10;
console.log(c);
}
example1();
Here in the example1() function, we’ve got an error: Uncaught ReferenceError: c is not defined. This is because the reference for the variable c doesn’t exist in the local or global scope & we are trying to use it.
Let’s see this via another code example.
function example2(a,b) {
const sum = a + b + c;
console.log(sum);
}
example2();
How can we avoid ReferenceError?
- Instead of directly accessing a variable, we should first check whether the variable exists in the scope or not.
- We can use typeof, which helps to find the type of a variable. If we get typeof variable as undefined, then it means that the variable hasn’t been initialized yet.
TypeError
We’ll also first understand this by an example. Can you add a number with a number that doesn’t exist in the memory? It’s not possible to do so. Similarly, In Javascript TypeError occurs when the variable exists but the operation you are trying to perform is not appropriate for the type of variable.
Let’s see some code examples for this.
function example3(a) {
console.log(b.substring(0,2));
var b = a;
}
example3(5);
In function example3(), b will be undefined till it is declared because the variable declared with var is hoisted in function scope & is undefined until it’s initialized. So, we can’t perform any operation on undefined, therefore b.substring(0,2) will give a TypeError.
How to avoid TypeError?
- TypeError can be prevented by using a static type checker, like by writing your code in TypeScript.
- Using let instead of var i.e. initializing a variable before using it can prevent TypeError from occurring.
Source: hashnode.com