What is an error in JavaScript?
An error in JavaScript is an object that represents a problem that occurred while the program was running. When JavaScript hits a situation it cannot handle (for example, dividing by zero, referencing a nonexistent variable, invalid syntax, and so on), it creates an error object and "throws" it. If the error is not "caught", code execution stops.
The basic idea
Errors exist to control unforeseen situations - so the program does not "crash" unexpectedly, but can handle the problem and keep running correctly.
Example of an error occurring
console.log(a); // ReferenceError: a is not definedHere the variable a is not declared, so the interpreter creates and throws a ReferenceError.
Handling errors (try...catch)
So the program does not stop, errors can be handled with a try...catch construct:
try {
let result = JSON.parse("invalid JSON");
} catch (error) {
console.log("An error occurred:", error.message);
}In this example the program does not crash, it simply prints a message:
An error occurred: Unexpected token i in JSON at position 0Main error types
| Error type | When it occurs |
|---|---|
| ReferenceError | Referencing a nonexistent variable |
| TypeError | Wrong data type (for example, calling something that is not a function) |
| SyntaxError | An error in the code's syntax |
| RangeError | A value out of its allowed range |
| EvalError | Incorrect use of eval() |
| URIError | An error while working with URI-encoding functions (decodeURI, encodeURI) |
Creating your own errors
You can create and throw an error yourself with throw:
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero!");
}
return a / b;
}
try {
divide(5, 0);
} catch (err) {
console.log(err.message); // Cannot divide by zero!
}Key methods and properties of the Error object
| Property | Description |
|---|---|
name | The error type's name (TypeError, ReferenceError, etc.) |
message | The error description |
stack | The stack trace (shows where the error occurred) |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.