Debugging And Handling Errors In JavaScript

Tags: javascript, tutorial, webdev
Published: 2021-06-17 16:56:09

## **Introduction**
As a developer or programmer, Errors are essentially part of our daily lives, and getting errors in our code does not really mean that we're not proficient. An error in your code most times, simply means you’re trying to do something that might be a little complicated (or very complicated), and it doesn’t quite work yet or you made some important ommissions in your code. Learning from our mistakes is actually a good thing because it helps to strengthen our knowledge and also gives us the ability to help others out when they run into similar issues. In this article, we'll be discussing errors in Javascript and how to handle them.

## **Types of Errors in Javascript**

There are seven types of built-in errors in javascript, but we will be looking at the three common types in this article. You can check out  [javascript documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) for more insights.


- **SyntaxError:**This error occurs when the syntax of a particular language is not met. This error is usually thrown when there are typos, mismatched brackets or curly braces, or missing semi-colons in our code.


```
function test{
    console.log('this code will throw a syntaxError')
}
test()
``` 

```
/Users/dharmelolarezekiel/Desktop/test.js:1
function test{
             ^

SyntaxError: Unexpected token '{'

This code is throwing an error because a bracket 
is supposed to be after the test function.
``` 


```
for(let i = 1, i<10; i++){
    console.log(i)
}
```

```
/Users/dharmelolarezekiel/Desktop/test.js:1
for(let i = 1, i<10; i++){
               ^

SyntaxError: Identifier 'i' has already been declared

An error is being thrown because we used a comma 
instead of a semi-colon after declaring the variable **i**
``` 


- **ReferenceError :**
This type of error occurs when you're trying to reference an invalid value. e.g calling a variable that was not defined. In some cases, the variable could be defined and you'll still get a reference error and this is usually the effect of scoping because when you declare a variable with **let/const**, such variable can not be accessed outside the function where it is declared.


```
let ageRange= 25
if(ageRange>= 25){
    console.log('you are old enough')
}
console.log(AgeRange)
``` 

```
/Users/dharmelolarezekiel/Desktop/test.js:5
console.log(AgeRange)
            ^

ReferenceError: AgeRange is not defined

This code is throwing an error because the variable 
that was defined and the one that was called are different 
from each other even though they are spelled the same way.
``` 

```
function ageRange(){
    let age1= 25;
    let age2= 20
    return age1 * age2
    }

  console.log(age2)
``` 

```
/Users/dharmelolarezekiel/Desktop/test.js:7
  console.log(age2)
              ^

ReferenceError: age2 is not defined

In this case, although age2 is defined we still got an error 
that says it is not defined. This is because age2 was defined
in a function and it cannot be accessed outside the function
``` 

- **TypeError:**This error is thrown when the value passed to an expression is not the expected type. e.g using a string method on a number.


```
let variable = 25
console.log(variable.toUpperCase())
``` 

```
/Users/dharmelolarezekiel/Desktop/test.js:2
console.log(variable.toUpperCase())
                     ^

TypeError: variable.toUpperCase is not a function
``` 
## **Debugging errors in Javascript**

In order to debug errors in javascript, there are few things you should do first. Luckily, the console always comes to the rescue here. 

- **In what line did the error occur:** This is usually the first thing to look out for when trying to debug. The console always points out the particular line where the error is.

```
/Users/dharmelolarezekiel/Desktop/test.js:2

In this case, our error is line 2 of our test.js file
``` 

- **What type of error was thrown:** After finding out the line where the error occurred, the next thing to do is check what type of error was logged to the console.

```
ReferenceError: age is not defined
``` 

- **What is the error message logged**: This will enable you to debug with ease since you already know the type of error you're dealing with.

## Handling Errors In Javascript


> 
Error handling is the anticipation of errors and addressing them accordingly. 
                                                                                                         "Codecademy"

Error handling is mostly used when working with data from other sources or user inputs as the source code can be unreliable. When a code is being executed and it throws an error, that error is referred to as **runtime error**. I'll be highlighting the different ways of handling errors and these are:


- **try... catch statement**

```
try{
    // piece of code
}catch(err){
   //error handling
}
``` 
What this block of code does is that it first runs our code in the try block and if it goes smoothly, the catch block will be ignored. But if an error occurs, the try block stops executing and the handling process begins from the catch block and the **err**(any name can be used) will log an error object that details what went wrong with the code. The try...catch statement does not stop our code from running because we have handled the error with the **catch(err)** block.


- **Throw statement:** The throw keyword can be used to throw an error and halts the program from working. It can also be used to throw an error with a user-defined message. If you use throw together with try and catch, you can control program flow and generate custom error messages.