Difference between TypeError and ReferenceError

Difference between TypeError and ReferenceError

In Javascript, both TypeError and ReferenceError are types of errors that occur at runtime.

TypeError:

As the name suggests TypeError occurs when a value is not of an expected TYPE. For example, if we try to call a non-function value as a function.

const a=10;
a(); // TypeError: a is not a function

Every time, the type of an operand or an argument won't be what was expected a TypeError would be thrown.

Cases when TypeErrors are thrown:

  1. Calling a non-function value as a function:

     const a=10;
     a(); // TypeError: a is not a function
    
  2. Performing an operation on incompatible types:

     let a= "3";
     let b= 3;
     let c=a+b; // TypeError: a is a string and b is a number, they cannot be added
    
  3. Using an object that does not have the property or function that you are trying to access:

     const obj={};
     obj.property(); //TypeError: obj.property() is not a function
    
  4. Accessing an index on an object that is not an array:

     const obj={};
     obj[0]; //TypeError: obj is not an array-like object
    
  5. Converting a value to a type it cannot be converted to:

let a="not a number";
let b= Number(a); //TypeError: a cannot be converted into a number

ReferenceError:

A ReferenceError in JS occurs when you try to access a variable that has not been declared.

Cases when ReferenceError occurs:

  1. You misspelled the variable name:

     let message="Hello, World!";
     console.log(nessage); 
     // Throws a ReferenceError because of misspelled variable name
    
  2. The variable was declared in a different scope. If the variable is declared within a block of code, it won't be accessible outside that block:

  3.    let message = "Hello, World!";
    
       if (true) {
         let message = "Goodbye, World!";
       }
    
       console.log(message); // "Hello, World!"
    
  4. The variable is not yet declared: if you try to access a variable before it has been declared, a ReferenceError will be thrown:

     console.log(message); // Throws a ReferenceError
    
     let message = "Hello, World!";
    
  5. The variable is declared but assigned a value of "undefined": If you try to access a property of an object that has not been declared, a ReferenceError:

     let user;
    
     console.log(user.name); // Throws a ReferenceError
    

Conclusion:

A TypeError in JavaScript occurs when you try to use a value in a way that it cannot be used, while a ReferenceError occurs when you try to access a variable that doesn't exist.