Recognize Syntax, Reference and Logic Errors
Recognize Syntax, Reference and Logic Errors
A syntax error prevents parsing; a reference error can occur when a name is unavailable; a logic error can produce the wrong school result without throwing. Identify which stage fails before choosing a fix.
Before this topic, review Cancel Unneeded Requests if its terms are unfamiliar.
What you’ll learn
- Explain recognize syntax, reference and logic errors through the school example.
- Trace the shown operations and distinguish their result from displayed output.
- Make the practice change and explain its consequence: The value is now available directly, so the try block prints it without throwing.
Work through the school example
This is JavaScript using language features and the host console. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.
JavaScript · school.js · complete example
try {
console.log(missingMark);
} catch (error) {
console.log(error.name);
}
Expected output
ReferenceErrorRun in JavaScript compiler →Introduction
Errors are inevitable in programming. In JavaScript, errors can occur due to typos, invalid operations, missing variables, or unexpected behavior at runtime.
Understanding error types and how to catch them is important to writing reliable code. JavaScript offers built-in mechanisms like try...catch to help developers gracefully handle unexpected issues.
Types of Errors in JavaScript
- ReferenceError: Occurs when a variable that hasn’t been declared is accessed.
- TypeError: Happens when an operation is performed on a value of the wrong type.
- SyntaxError: Raised when JavaScript code has invalid syntax.
- RangeError: Happens when a value is out of an allowable range.
- EvalError: Related to the
eval()function (rarely used today). - URIError: Occurs when functions like
decodeURI()orencodeURI()are misused.
1. ReferenceError
This error is thrown when you try to access a variable that hasn’t been declared.
// ReferenceError Example
try {
console.log(userName); // userName is not defined
} catch (error) {
console.error("Caught a ReferenceError:", error.message);
}
Caught a ReferenceError: userName is not defined
2. TypeError
Thrown when a value is not of the expected type. For instance, calling a method on undefined.
// TypeError Example
try {
let num = 42;
num.toUpperCase(); // toUpperCase() is a string method
} catch (error) {
console.error("Caught a TypeError:", error.message);
}
Caught a TypeError: num.toUpperCase is not a function
3. SyntaxError
Occurs when the code structure is not valid JavaScript. These errors must be caught at eval-time.
// SyntaxError Example using eval
try {
eval('function () {'); // invalid syntax
} catch (error) {
console.error("Caught a SyntaxError:", error.message);
}
Caught a SyntaxError: Unexpected token ')'
4. RangeError
Thrown when a number is outside of its allowable range, e.g., when creating an array with invalid length.
// RangeError Example
try {
let items = new Array(-5);
} catch (error) {
console.error("Caught a RangeError:", error.message);
}
Caught a RangeError: Invalid array length
5. URIError
Happens when decodeURI or encodeURI is used incorrectly.
// URIError Example
try {
decodeURI('%'); // invalid URI component
} catch (error) {
console.error("Caught a URIError:", error.message);
}
Caught a URIError: URI malformed
How to Catch Errors
JavaScript provides try...catch to handle errors:
try {
// risky code here
} catch (error) {
// handle error here
console.log("Error caught:", error.message);
} finally {
console.log("This block always runs");
}
What Happens If You Don’t Catch an Error?
If errors are not caught using try...catch, JavaScript will stop execution and show the error in the console. In production, this could mean breaking your entire web page or script.
Questions and Answers
Q: Can all errors be caught with try...catch?
A: No, SyntaxError that occurs outside eval cannot be caught using try...catch. Also, asynchronous errors need special handling (like .catch() for Promises).
Q: Can you throw custom errors?
A: Yes, using throw. You can throw a string, number, object, or an instance of Error.
try {
throw new Error("This is a custom error");
} catch (e) {
console.log("Custom Error:", e.message);
}
Custom Error: This is a custom error
Conclusion
By understanding error types and handling them effectively, you can make your JavaScript programs more robust and user-friendly. Mastering try...catch and identifying error patterns is an essential skill for every developer.
Recognize the important boundary
A syntax error in the same source cannot be caught by a try block that never parsed. Avoid publishing raw personal data in diagnostic logs.
Try a small variation
JavaScript · original source for practice
try {
console.log(missingMark);
} catch (error) {
console.log(error.name);
}
Your task: Replace missingMark with 72. Predict the result before running the edited program.
The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.
Worked answer and reasoning
The value is now available directly, so the try block prints it without throwing.
JavaScript · complete worked variation
try {
console.log(72);
} catch (error) {
console.log(error.name);
}
Expected output
72Run in JavaScript compiler →Predict the original program
JavaScript · original program for this question
try {
console.log(missingMark);
} catch (error) {
console.log(error.name);
}
Keep the useful idea
A syntax error prevents parsing; a reference error can occur when a name is unavailable; a logic error can produce the wrong school result without throwing. Identify which stage fails before choosing a fix.
Check your variation against this explanation: The value is now available directly, so the try block prints it without throwing.
Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.
Reaching the recap and completing the quizzes are separate milestones.