try {
throw new Error();
}
catch(err) {
console.log(err)
}
console.log("This line now runs")
Syntax, logical and runtime errors
Here are some of the most common errors in JavaScript:
- ReferenceError
- SyntaxError
- TypeError
- RangeError
There are some other errors in JavaScript. These other errors include:
- AggregateError
- Error
- InternalError
- URIError
ReferenceError
A ReferenceError gets thrown when, for example, one tries to use variables that haven’t been declared anywhere.
An example can be, say, attempting to console log a variable that doesn’t exist:
console.log(username);
SyntaxError
Any kind of invalid JavaScript code will cause a SyntaxError.
var a "there's no assignment operator here";
There’s an interesting caveat regarding the SyntaxError in JavaScript: it cannot be caught using the try-catch block.
TypeError
A TypeError is thrown when, for example, trying to run a method on a non-supported data type.
A simple example is attempting to run the pop() method on a string:
"hello".pop() // Uncaught TypeError: "hello".pop is not a function
RangeError
A RangeError is thrown when we’re giving a value to a function, but that value is out of the allowed range of acceptable input values.
Undefined, null and empty values
Null
Intentional absence of any object value.
Defensive programming
Defensive programming is all about assuming that all the arguments a function will receive are of the wrong type, the wrong value or both.
Additional resources
Here is a list of resources that may be helpful as you continue your learning journey.