What is the difference between Type Error and Reference Error in JavaScript?

What is the difference between Type Error and Reference Error in JavaScript?

In javascript, several different kinds of errors can arise. But when I'm working with javascript, these two errors are the ones I experience most frequently in my browser. In general, typeErrors and Reference Errors are runtime errors, which arise as the code is being executed.

Type Error:

A type error happens when two types aren't compatible, for as when you wanted to access a variable with one datatype but mistakenly declared it with another. In some circumstances, JavaScript will automatically execute type conversion to permit an operation to proceed without raising a type error.

Here are some examples of when a type error is thrown:

  1. When attempting to modify a value that can't be modified.

     const name="Bijaylaxmi";
     name="Laxmi" //This will throw a "TypeError: Assignment to constant variable" error
    
  2. A non-function is called as a function.

     let x = 42;
     x(); // This will throw a "TypeError: x is not a function" error.
    
  3. Converting a value to a type cannot be converted to.

     console.log(Number("hello")); // This will log "NaN"
    

Reference Error:

When you declare a variable in JavaScript, a memory location is assigned to hold the value of that variable. A reference error will occur if you attempt to access a variable that hasn't yet been declared or given a value since its name doesn't yet correspond to a memory address.

Here are some examples of when a reference error is thrown:

  1. Using a variable that hasn't been declared yet.

     console.log(x); // ReferenceError: x is not defined
    
  2. A variable or function being used outside of its scope.

     function printNumber() {
       var a = 10;
     }
     console.log(a); // ReferenceError: a is not defined
    
  3. Incorrect spelling of a function or variable name.

     const number=22;
     console.log(numbr); //ReferenceError: numbr is not defined
    

Conclusion:

When you perform an operation or use a value of a type that is not valid or does not support that operation, you get a TypeError, whereas a ReferenceError occurs when you try to access a variable or function that has not been declared or defined.