Introduction
Development and coding go hand in hand! We encounter errors on the Chrome browser console or in our terminal and there's no escape to it!
It's good to be mindful of the errors that pop up because it would help us identify the root cause quickly!
The prominent errors are-
Range error
Type error
Reference error
Syntax error
URI error
Internal Error
Eval Error
We would broadly look at two errors- Type error and Reference error.
Type Error
Type errors occur when the operation is performed on the wrong data type.
In the above example, name
is a constant variable which means the value can't be changed. However, if I try to reassign a value to it, it throws a Type error because it's a wrong operation on a const.
Let's look at another example.
toLowerCase()
operates on the string data type. Here, I am trying to execute toLowerCase()
on a number data type, which is a wrong data type scenario.
Real-life scenario- If you ask for chicken biryani at a pure veg restaurant, what would you get apart from being called ridiculous?๐
You will not get chicken biryani because it's a Type error . The operation that you performed is on the wrong restaurant (data type).
Reference Error
Reference errors occur when we try to access a variable that doesn't exist in the current scope.
Quick explantion for scope-
Every block in JavaScript is defined by curly braces {}. When a value is defined within function it is called functional scope where as if it's defined within a
if
orswitch case
block it is defined as block scope.
In JavaScript when a variable is declared, we store it in the memory. When we reference that variable, it looks for it in the memory. If it is not there, it throws a reference error.
For example,
a is present but what about b? It's not there, hence we get the error.
When we declare a variable with let
, its existence is limited only to the scope in which it is declared. In the above example, we have another let a
inside the block which isn't initialized before it is accessed, hence we get the reference error.
A few examples of Reference errors are-
Case 1: A variable is accessed without defining it.
Case 2: Accessing the wrong variables.
Basic rules to avoid errors
Try to declare variables at the top of the scope.
Use different names to declare variables.
Be aware of the operations that you're performing
Closing thoughts
I hope the explanations helped you in distinguishing the two errors- Type error and Reference error. Please let me know if I have missed anything!
References
MDN- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError
https://blog.bitsrc.io/types-of-native-errors-in-javascript-you-must-know-b8238d40e492