Type Error vs Reference Error in JavaScript

Type Error vs Reference Error in JavaScript

While coding in JavaScript, you must have encountered many errors in the browser console. There are different types of errors. However, in this blog, I'd like to focus on type errors and reference errors.

Type Error:

In JavaScript, a "Type error" occurs when we try to operate on a value that is not of the expected type. For example; if we are passing the wrong arguments to a function, performing invalid operations on variables, or trying to access a property of a value that is not an object.

In simpler terms, we can say, a type error occurs when a value is of the wrong type for a particular operation.

Example:1

In this example, "name" is a const variable that contains a string, but we are attempting to access "name" as a function. As a result, we get a type error because we are attempting to access the name as a function.

Example:2

In this example, "number" is a constant variable that holds a number value. However, in the second line of code, we can see that we are attempting to operate on a number, where we are trying to convert the number to UpperCase. This is completely inappropriate. I hope we're all aware that we won't be able to change any numbers to UpperCase. As a result, we'll get a type error.

Reference Error:

In JavaScript, a "Reference Error" occurs when we try to use a variable or a function that has not been declared or is not in scope.

Example:1

In this example, we are trying to access the value of the variable "unknown" before declaring or initializing it. Hence when we run the code Javascript engine will throw a Reference Error.

Example:2

In this example, we have declared and initialized the value of variable "x" but we are attempting to access it outside the function scope. As a result, we'll get a Reference Error.

Conclusion:

Two of the most common JavaScript errors are TypeError and ReferenceError. Understanding this error better will allow you to debug the code more easily and write clean and robust code.