Errors

Three common error types in JavaScript

1. SyntaxError

You’ll get this error when there’s a typo creating invalid code, which the compiler cannot interpret.

To solve this error, check if you properly opened and closed all brackets, braces, parentheses, and semicolons.

2. ReferenceError

You’ll get this error if you try to use a variable that does not exist.

To solve this error, check if all variables are properly declared.

3. TypeError

You’ll get this error if you attempt to perform an operation on a value of the wrong type.

For example, if you try to use a number method on a string, you’ll get TypeError.

How to identify the error’s type, description, and location

  1. Check the line the error occurred.

You can almost always find this information on the first line in the following format <file path>/<file name>:<line number>.

For example, the location is app.js:1. So, an error is in the file named app.js on line 1.

  1. Check the type of error

  2. Check the error message

For example

/home/script.js:5
if (num > total;) {
                     ^

SyntaxError: Unexpected token ;

In the example above:

  • File that has error: script.js
  • Line that has error: 5
  • Type of error: SyntaxError
  • The description of the error: Unexpected token ;

Debug

To debug an error, you should follow these steps:

  1. Run your code. Identify the error’s type, description, and location.
  2. Go to the file name and line number indicated by the error stack trace. Using the error type and description, identify the bug in your code.
  3. Fix the bug and re-run your code.
  4. Repeat steps 1-3 until your code no longer throws any errors.

Tips

  • If you find a silent bug (your code returns incorrect values), try console.log() on each line.
  • You can also check Javascript documentation or ask questions on Stack Overflow to solve the error.

Construct an error

You can use the Error() function to create the error object or use the new keyword with the Error().

console.log(Error("Message goes here"));
// OR
console.log(new Error("Message goes here"));

Throw an error

To throw an error and halt the program from running in JavaScript, we use the throw keyword:

throw Error("Something wrong happened");

Handle errors

We can use try...catch statement to anticipate and handle errors.

  • Evaluating code in a try block to anticipate errors.
  • Catching the error in a catch block allows our program to continue running.

The syntax for a try…catch statement:

try {
  // try block code
} catch (e) {
  // catch block code
}
try {
  throw Error("This error will get caught");
} catch (e) {
  console.log(e);
}
// Prints: This error will get caught