Understanding JavaScript Errors and How to Handle Them
JavaScript Errors Errors Are Inevitable When you execute JavaScript code, various errors may arise. These can result from mistakes in coding, incorrect inputs, or unexpected occ...
JavaScript Errors
Errors Are Inevitable
When you execute JavaScript code, various errors may arise. These can result from mistakes in coding, incorrect inputs, or unexpected occurrences. Common JavaScript errors include:
- Reference Errors
- Type Errors
- Range Errors
- URI Errors
- Syntax Errors
- Eval Error (deprecated)
- Silent Errors (discussed later)
Handling JavaScript Errors
To manage errors effectively, JavaScript provides the try and catch statements. The try block contains code that may throw an error during execution. If an error occurs, the catch block executes, allowing you to manage the error gracefully.
Reference Errors
A ReferenceError is thrown when a script attempts to reference a variable that is not defined. Examples:
// Example of ReferenceError
fname = foo; // foo is not defined
let x = y; // Cannot access 'y' before initialization
let y = 5;
Type Errors
A Type Error occurs when a variable or parameter is not of a valid type, or an operation is not allowed on a type. Examples include:
// Example of TypeError
anna(5); // anna is not a function
let num = 1;
num.toUpperCase(); // num.toUpperCase is not a function
Range Errors
RangeError is thrown when a numeric variable or parameter is outside of its valid range. Examples:
// Example of RangeError
new Array(-1); // Invalid array length
num.toPrecision(500); // toPrecision() argument must be between 1 and 100
URI Errors
A URIError occurs when illegal characters are used in a URI-related function. Examples:
// Example of URIError
decodeURI("%%%"); // URI malformed
Syntax Errors
SyntaxError is raised when there is a mistake in the syntax of the code, which violates JavaScript's grammatical rules. Examples include:
// Example of SyntaxError
fname = "John); // Invalid or unexpected token
Math.round(4.6; // Missing ')' after argument list
Syntax Errors are Not Catchable
- Syntax errors occur before the script runs.
- They are detected before
try...catchblocks can execute, meaning the script will fail to start.
JavaScript Eval Error
An EvalError relates to issues with the eval() function. However, in modern JavaScript versions, EvalError is not commonly thrown. Use SyntaxError instead.
Further Reading
Explore more about JavaScript errors:
- Silent Errors
- JavaScript Error Statements
- JavaScript Error Object
- JavaScript Debugging