Error Handling in JavaScript

In this section of the tutorial, we will discuss Error Handling in JavaScript and their different types such as syntax errors, runtime errors, logical errors in a JavaScript program with some good examples for in-depth understanding.

Error Handling in JavaScript

Many times while writing a program in JavaScript language, like any other language, a user can fall in the trap of making mistakes in the code and thus resulting in JavaScript throwing errors. These situations can be quite confusing for the user to handle.

These errors are bound to happen mostly when code is in a very dense amount, this is where the chances of something going wrong increases. Adding to it, the process of refining the code in order to find these typos and errors in the program is also a difficult task to do.

But regardless of the difficulties, JavaScript comes with many features that we can use to reduce these errors in our programs. Also, with rich knowledge of using syntax and logic, we can reduce such errors in a program.

In the following sections, we will discuss common errors in JavaScript and how to deal with them.

Undefined Variables

In case, we don’t use the keyword var while defining a variable in the JavaScript code, it will cause a syntax error.

We will take an example to understand the nature of this syntax error.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

a = 23;

document.write(a);

</script>
</head>
<body>
</body>
</html>
  • Here, we can clearly see that we have missed the keyword var in before defining the variable a, which will throw a syntax error.
  • The first kind of error that happens is related to missing syntax in the JavaScript code. While defining the variable, we must use the keyword var, and then we can assign any value to it or use it in the program further.

We will take an example to understand how we can avoid the syntax error by using proper keywords,

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

var a = 23;

document.write(a);

</script>
</head>
<body>
</body>
</html>
  • Here, we clearly see that variable a is defined using the keyword var before.

Case Sensitivity

Case sensitivity is the major source of errors in JavaScript. There are higher chances for a user to commit a typo while writing case-sensitive characters in a program, which will cause errors in the program. And this kind of error is difficult to trace in a program.

We will take an example to understand the case-sensitive error in a program.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

var a = "One";

If (a == "one"){
    document.write("True");
}

</script>
</head>
<body>
</body>
</html>
  • Here, we can clearly see that error in case sensitive string in line 8, it is written If instead of if and one instead of One.
  • So in the above code, there will be errors such as object expected or not defined. So, we must be careful while writing case-sensitive characters in a JavaScript program.

Incorrect Number of Closing Braces

This error happens when a user uses loop statements like if, for, do while. And misses closing the braces properly.

We will take an example to understand the closing braces error in a program.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

function myFunction()
{
    x = 1;
    y = 2;
    if (x <= y)
    {
        if (x == y)
        {
        alert(“x equals y”);
        }
}
myFunction();

</script>
</head>
<body>
</body>
</html>
  • Here, we can clearly see that there is a missing closing brace in line 16. This does not close the if statement and will cause a syntax error.

Incorrect Number of Closing Parentheses

Similarly, this error happens when a user misses using proper parentheses for closing a conditional expression.

We will take an example to understand the closing parentheses error in a program.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

function myFunction()
{
    x = 1;
    y = 2;
    if (x <= y)
    {
        if (x == y
        {
        alert(“x equals y”);
        }
        
}
myFunction();

</script>
</head>
<body>
</body>
</html>
  • Here, we can clearly see that in line 12, there is a missing closing parentheses in the conditional expression of the if statement which will throw a syntax error in the program.

Using Equals (=) Rather than Is Equal To (==)

This error happens when we confuse using assignment operator with equality operator and vice versa. This is a very common error.

We will take an example to understand the above error in a program.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

function myFunction()
{
    x = 1;
    y = 2;
    if (x <= y)
    {
        if (x = y)
        {
        alert(“x equals y”);
        }
        
}
myFunction();

</script>
</head>
<body>
</body>
</html>
  • Here, we can clearly see that in line 12, there is a = missing which makes it an assignment operator instead of an equality operator that we want to use logically.

Using a Method as a Property and Vice Versa

This is another common type of error that is seen in JavaScript programs. It happens when a user confuses using a method as a property and vice versa in a program.

It mostly happens when a user either forgets to put parentheses after a method with no parameters or uses a property and puts parentheses after it.

We will take an example to understand the above error in a program.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

var nowDate = new Date();
alert(nowDate.getMonth);


</script>
</head>
<body>
</body>
</html>
  • Here, we can clearly see that in line 7 a pair of parentheses is missing in calling the getMonth() method.

Missing Plus Signs During Concatenation

This error happens when a user misses putting plus signs during the concatenation of string values in a JavaScript program.

We will take an example to understand the above error in a program.

Example:

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">

var x = "WELCOME ";
var y = " TO ";
var z = "CODEDEC";


console.log(x+yz);

</script>
</head>
<body>
</body>
</html>
  • Here, we can clearly see that in line 11, a plus sign + is missed between y and z while concatenation of string value present in both the variables.

Preventing Errors in JavaScript

Now that we are well informed about the possible types of errors that can occur in a JavaScript program. We can prevent errors by avoiding making any such typos in the first place.

However, there are a few things that we should do to ensure an error-free program:

  • By thoroughly checking our JavaScript code by running it into as many browsers as possible.
  • We can simply optimize our code for few commonly used browsers that should support the webpages and then verify if the code works in those browsers.
  • If for some reason, our code is not compatible with any web browser, then we should simply add a note in the documentation for the user to know about the best browser compatibility of the code.
  • Validating the data that is to be parsed in the web pages is also important to avoid any errors or program failures.

Debugging in JavaScript

There are many tools that are readily available to developers to debug JavaScript code. Many debugging tools are provided by browsers such as Firefox, Safari, Chrome, and Opera.

Using such tools, a developer can easily halt the execution of the script with breakpoints and then step through the flow of code to observe the error.

Debugging is generally universal across all browsers. Most of the features offered are common across all browsers.

In the next section of the tutorial, we will discuss Regular Expressions in JavaScript and their different types which are used to match the character combinations in strings in a JavaScript program with some good examples for in-depth understanding.