JAVASCRIPT- ReferenceError vs TypeError

JAVASCRIPT- ReferenceError vs TypeError

Overview

In Javascript, it's common to encounter errors that can be challenging to debug. Of all errors, ReferenceError and TypeError is the two common error that we frequently face while working on the browser console. In this blog, we will discuss the root cause and also how to deal with them.

ReferenceError

A ReferenceError occurs when you try to access a variable or function that has not been declared or has not yet been assigned a value. Literally, it occurs when you try to use a variable or function that doesn't exist at all or mistype a variable or function name.

const a = "hello"
console.log(b) // ReferenceError : b is not defined

b() // ReferenceError : b is not defined

In the above example, we can see that variable b was never defined nor function c was declared, and so when we call the variable b or call the function b, it throws the ReferenceError.

TypeError

A TypeError, on the other hand, occurs when you try to use a value of the wrong type or perform an operation on a value that is not allowed. Literally, it occurs when the variable exists, but the operation we're trying to perform is not appropriate for the type of value it contains.

const a = "hello"
a() // TypeError : a is not defined

var c = undefined
c.length // TypeError : Cannot read properties of undefined (reading 'length')

In the above example, we can see that variable a was defined as a string but when we try to run it as a function it throws the TypeError similarly variable c was defined as undefined and so when we try to check the length, it throws the TypeError as the typeof c is undefined and undefined doesn't possed any length.

Difference between ReferenceError and TypeError

The main difference between ReferenceError and TypeError is that ReferenceError occurs when we try to access a variable or function that doesn't exist at all while TypeError occurs when we try to perform an invalid operation on a variable or function.

Dealing with ReferenceError and TypeError

When we encounter ReferenceError, we need to check if the variable or function has been defined and if there is any mistype in the name. if the variable or function hasn't been defined we need to define it somewhere in the code. If there is any mistype in the name we have to correct it.

When we encounter TypeError, we need to check the error message to understand what's causing the error. The error message will tell us the line number and the type of error. We need to fix the error by correcting the type of the value or by checking if the property or method exists on the object.

Conclusion

In conclusion, ReferenceError and TypeError are common in Javascript development and it's essential to understand the differences between them and also how to deal with them. By understanding these errors, we can write better and more robust code. Eager to know more about Javascript error types? please click here