ReferenceError vs TypeError In JavaScript

ReferenceError vs TypeError In JavaScript

while writing a javaScript code we often come across two errors i.e ReferenceError and type Error in our console.

Let's try to understand when these two error occurs individually.

ReferenceError

Let's try to decode the name of an error. Reference means pointing to some memory location or technically having the address(access) of some memory location and an error generally occurs when some illegal happens in a program so, it is very clear that a reference error occurs when we try to reference a variable which doesn't exist

Reference errors are the errors that occur when the compiler is not able to find a reference of any particular variable.

var a=22
console.log(b)

Here, we are trying to print a variable b which is not yet been declared and hence we got a reference error

const function1=()=>{
    let a=2
    let b=4
    console.log(a)
}
console.log(b)

Here, In the above example, although we have defined a variable a and b their scope is inside a function(named function1) and we have no reference to a and b outside a function. Hence, if we access them outside we get a reference error.

TypeError

Let's again decode the name as the name suggest type which here means Data-type so, whenever there is type incompatibility we get TypeError.

TypeError occurs when the value for operating is not of the expected type.

code example:

let a={a:1,b:2,c:3}
a.push("22")

Here, we try to push a string into an object which is type incompatibility and hence, got TypeError.

In this article, we tried to understand the difference between TypeError and ReferenceError to make our debugging easy and concepts clear.