Essential JavaScript
Introduction
JavaScript Basics
Numbers
Strings
Logic
Variables
Loops
Objects
Arrays
Going Further
Essential JavaScript
Introduction
JavaScript Basics
Numbers
Strings
Logic
Variables
Loops
Objects
Arrays
Going Further
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:
console log("Hello World");
This code throws an error because JavaScript can't execute it properly.
Types of Errors
The code above throws this error:
SyntaxError: Unexpected identifier 'log'
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 that:
- The error is a SyntaxError, meaning our code is not valid JavaScript
- The error is caused by the word "log"
JavaScript expects code to follow certain rules and patterns. If we don't follow the rules, we break the code with a SyntaxError.
Handling Errors
How you handle an error depends on what kind of error it is.
For a SyntaxError
, we need to fix our code. The correct syntax for logging to the console is console.log
, with a period before log
. When we add that missing character, the code will run again.
Try / Catch
Some errors happen when your program is already running.
For example:
log("This throws an error.");
The above code will run, but it will throw an error because log
doesn't exist (it's console.log
, remember?):
ReferenceError: log is not defined
For those errors, you can use something called a try...catch statement to "catch" errors and handle them.
However, if possible we should always write code that doesn't cause errors. Errors help us find problems and fix our code. If we see an error, we should update our code to avoid throwing that error again.
None of the lessons in this course require you to use try...catch statements.
Learning Goals
I know what an error is
I can use an error message to see where the error came from
Code Editor
Click "Run Code" to execute your JavaScript in a secure sandbox and see the output below.
Console Output
0 output lines