Essential JavaScript

Errors

When we write code, the computer might have trouble following our instructions.

If we make a mistake in our code, or if something unexpected happens when our code is running, we could get an error.

When an error happens, the code stops running.

Run this example code:

7 7

This code throws an error because JavaScript can't execute it properly.

Types of Errors

The code above throws this error:

SyntaxError: Unexpected number [solution.js:1:3]

JavaScript will throw different types of errors for different problems. This one is a SyntaxError.

Errors often have helpful messages that point to where the error happened.

This one tells us several things:

  • the error was caused by an unexpected number
  • the error happened in the solution.js file (meaning the practice editor)
  • the error happened on line 1, column 3

That means JavaScript found this error at the third character on the first line. Specifically, the second 7 created this error.

There are two numbers but no operators in this code. We aren't adding or subtracting or doing anything else.

JavaScript expects code to be made of valid expressions. If we don't follow the rules, we break the code with a SyntaxError.

Handling Errors

There are ways to deal with errors in code and keep the program running.

You can use something called a try...catch statement to "catch" errors and handle with them.

However, if possible we should always write code that doesn't cause errors. Errors help us find problems and fix our code.

None of the lessons in this course require you to use try...catch statements.


Learning Goals

Code Editor