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.
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.
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.
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.
Check the type of error
Check the error message
For example
/home/script.js:5
if (num > total;) {
^
SyntaxError: Unexpected token ;
In the example above:
To debug an error, you should follow these steps:
Tips
console.log()
on each line.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"));
To throw an error and halt the program from running in JavaScript, we use the throw
keyword:
throw Error("Something wrong happened");
We can use try...catch
statement to anticipate and handle errors.
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