Table of contents
Here are two errors that I see in my browser console all the time when working with JavaScript.
There are tons of different JavaScript errors and they can be found in the Mozilla docs, here.
For this post, I wanted to specifically get into the difference between TypeError
vs ReferenceError
.
Reference Error :
In a case where a variable reference can't be found or has not been declared, then a reference error occurs.
When we create a variable, all we do is create a reference with a value. var a = "I'm a string"
tells the js compiler that any time it sees the variable a,
it is seeing a string with a value of "I'm a string".
without that variable declaration, js has no idea what to do when it comes across a
because there is no reference, so it throws an error.
Example:
var a = "I'm a string";
console.log(a) // I'm a string
console.log(b) // Uncaught ReferenceError: b is not defined.
Type Error :
In type error, the JavaScript compiler tells you that however you are attempting to use your variable is not how it is intended.
Example :
var a = "I am a string";
console.log(a) // I am a string
console.log(a()) // Uncaught TypeError: a is not a function
The error message is clean and tells you exactly what is wrong in this very simple example. You are trying to invoke a
as though it is a function, but yet, it is a lowly string.
What you are looking for is:
var a = function(){
return "I am a string"
}
console.log(a()) // I am a string
For example: if objects are treated as strings, or functions are treated as numbers, it might result in a type error.