Loading lessons...
Errors in JavaScript
Errors in JavaScript
Errors happen when something goes wrong in your code. JavaScript reports them so you can fix them.
Common error types
- SyntaxError: you wrote something JavaScript cannot understand.
- ReferenceError: you used a variable that does not exist.
- TypeError: you used a value the wrong way (like calling a number as a function).
- RangeError: a number is outside the allowed range.
- Error: a generic error.
Example ReferenceError
console.log(missingVariable);
// ReferenceError: missingVariable is not defined
Example TypeError
let n = 5;
n.toUpperCase();
// TypeError: n.toUpperCase is not a function
Errors stop the program
When an unhandled error happens, the script stops running at that point.
Reading an error
Errors usually include:
- The error type.
- A message explaining the problem.
- A stack trace showing where it happened.
The Error object
You can create errors yourself:
throw new Error("Something went wrong");
TL;DR
- Syntax, Reference, and TypeError are common errors.
- Errors stop the script unless handled.
- Errors include a type, message, and stack trace.
throw new Error(...)creates errors.