In order to understand Type Error vs Reference Error, first we will need to know Variable Declaration vs Variable Initialization.
var x;
In this above statement, we can say that x is declared but not yet initialized.
var x = 5;
Here, we can say that x is declared and as well initialized.
Now, let’s say we would want to access the x’s property that has been declared but not initialized.
var x; console.log(x);
This would result variable x to be
undefined
Now, let’s say that we would want to declare and initialize x to undefined and then access the x’s toString() method.
var x = undefined; console.log(x.toString());
This would result in
Uncaught TypeError: Cannot read property ‘toString’ of undefined(…)
Now, let’s say we would like to access the x’s property thats been been declared as well as initialized.
var x = 5; console.log(x.toString());
This would result
5 // Since 5 is declared and initialized as a number, //and we were trying to convert it to a String.
Now, let’s say we would want to access a variable y that doesn’t exist in the scope (meaning that there is not presence of variable y with out any initialization or declaration)
console.log(y);
This would result in
Uncaught ReferenceError: y is not defined(…)
Happy Learning 🙂