5 Types Of Errors In JavaScript – Method, Messages & Fixation Steps

  • Vidhi's profile image
    Vidhi
5 Types Of Errors In JavaScript – Method, Messages & Fixation Steps

It is inevitable to avoid errors while you are coding any programming language. Every coder till now must have dealt with errors and how to debug them. There are three main types of errors in programming. These errors are:

Syntax Errors

This error occurs when the programmer uses an already predefined syntax incorrectly. Syntax or parsing errors are those which occur at compile time in any programming language and at interpret time for JavaScript. In JavaScript when this error occurs then only the code contained in the same thread having the error is affected while the remaining codes in the other threads get executed as they are not dependent on the threads containing the syntax error. 

For example, a syntax error is thrown as the function is missing a closing parenthesis.

const ourFunc = () =>{
console.log("hello world")
// Missing ending } of the function

Runtime Errors

A Runtime error, also called an exception, always occurs after compilation or interpretation i.e. during the execution of the program. Unlike syntax errors, these errors not only affect the thread where the error occurs but also affect the further statements in the code resulting in sudden termination or crashing of the executed application. One can make use of try-catch blocks to handle runtime errors. Majority of the errors like TypeError, RangeError, and other errors that we will discuss further, come under runtime errors.

Logical Errors

Out of the three errors, logical errors are the most difficult to find. These errors are not the outcome of a syntax or runtime error but they occur when a programmer makes a mistake in the logic that the code works on. Due to this error, the desired result is not achieved. One can not make use of try-catch blocks to find these errors as it all depends on the programmer’s reasoning skills and the type of logic they have written. 

5 Common Errors in JavaScript

Now that we understood the different types of errors and how to solve them, here are the 5 most common error that occurs in JavaScript:

1. Reference Error (Uncaught ReferenceError: event is not defined)

When one uses a variable reference that can not be found, undeclared, or is outside of the current scope used when you receive a reference error. You can easily find the line of code where you have made this error using the command prompt.
printme();
// undefined function is called

2. Type Error (TypeError())

One can get type errors for various reasons like using an undefined function or when there is a reading length property for an undefined variable. Let’s understand the different reasons why a type error occurs.

  • When one tries to access an undefined variable then you will always receive an error in your command prompt saying “Uncaught TypeError: cannot set property of undefined”. This error is only thrown when you make use of the undefined variable.
    var foo;
    foo.value = 0;
  • When the length property is used for an undefined variable then the “Uncaught TypeError: cannot read property ‘length’ of undefined” is thrown on the console. One can only find the length of a defined variable or array. If the array or variable is declared and not initialized then the programmer will receive this error. One can avoid this error by initializing the variable properly beforehand. 
    var mystring;
    mystring.length;
  • When the compiler reads a property or calls a method on a null object then you get a “TypeError: ‘null’ is not an object” in your console. In JavaScript, null and undefined are two separate things, this is the reason you see two different types of error messages. Undefined means that a variable has been declared but not initialized or assigned to any value. On the other hand, null means that the value assigned to the variable is blank.
    Object.defineProperty({}, 'key', null);
    // TypeError: null is not a non-null object
  • When you call an undefined method, the “TypeError: Object doesn’t support property or method” is thrown. For this, you have to properly define the function before calling it.
    this.myfunc()

3. Evaluation Error (EvalError())

The current JavaScript Engine or the EcmaScript specification does not throw this error. But the EvalError object still exists in the backward compatibility. This error indicates that an error regarding the global eval() function has occurred. 
try {
throw new EvalError('error');
} catch (e) {console.log(e);}

4. Range Error (Uncaught RangeError)

This error occurs for two reasons when you call a recursive function that does not terminate and also when you pass a value to a function that is out of range. For instance, the function Number.toExponential(digits) accepts values between 0 and 100, if a value from outside this specified range is passed then the RangeError is thrown. One can only debug this error by passing a value that comes within the expected range of values.
var n = 3.5234;
console.log(n.toExponential(-20)); //range error thrown

5. URI Error

In JavaScript, the “URIError: malformed URI sequence” is thrown at the command prompt when the given URI encoding or decoding was not unsuccessful. This happens when the argument passed to the decodeURI(), encodeURI(), encodeURIComponent() or decodeURIComponent() is not valid or an incorrect character(s) has been used.
console.log(decodeURI("%hsinp")); // URIError thrown

Try and Catch Blocks

A try and catch block is one of the best ways to handle errors in JavaScript. It helps to identify an error without crashing your application. One can make use of the if-else statement but try/catch provides many benefits that if-else can not.

A try statement helps to test a block of a script for errors. While the catch statement helps to handle the error if present. All JavaScript error objects have two properties, the name of the error and the actual error message stating what is wrong with the program. For example, SyntaxError: Unexpected end of input. Here for the error object e, e.name is SyntaxError and e.message is Unexcepted end of input. Here is the syntax for try and catch statement:
try{
//.....
} catch(e){
//.....
}

Other than try and catch statements there is a throw statement that helps you to showcase your custom-made error. This error can be an object, string, or boolean. If there is an error, the catch statement will display the error you have thrown. Here is an example of how you can use the throw statement with try/catch blocks:
let number = ("What is your age?")
try{
if(isNaN(number)) throw "Please give a valid number"
else if (number<21) throw "You are underage for this ride" else if (number>60) throw "You old for this ride"
} catch(e){
alert(e) // displays error name and message in a alter box
}

Lastly, there is the finally a statement that acts like a base point or neutral ground for you try and catch blocks. Irrespective of what happens in the try and catch block, the code in the finally statement will run. Here is an example of how you can use the finally statement:
let n = prompt("given a number between 0 to 10")
try{
if (isNan(n)) throw new Error("not a number")
else if (n<0 || n>10) throw new Error("out of range")
else alert(n)
} catch(e){
alert(e)
} finally{
alert("This is the finally block")
}

Conclusion

While coding in JavaScript, errors are bound to occur. Sometimes the programs throw errors while other times’ programmers can cause errors. As programmers, we should not be disheartened when errors are thrown at us but take it as a stepping stone to becoming a better developer. 

One of the best ways to test for errors is to use try and catch blocks in your code. It helps to find the error. Other than trying to catch you can also make use of JavaScript’s built-in error object which provides the error details when an error occurs. It gives the name as well as the message of the error which is thrown.