TypeError vs ReferenceError vs SyntaxError in JavaScript: Key Differences
TypeError occurs when a value is not of the expected type, a ReferenceError happens when accessing an undefined variable, and a SyntaxError is raised when the code has invalid syntax that prevents parsing.Quick Comparison
Here is a quick overview of the main differences between TypeError, ReferenceError, and SyntaxError in JavaScript.
| Error Type | When It Occurs | Example Cause | When Detected | Common Message |
|---|---|---|---|---|
| TypeError | Using a value in an invalid way for its type | Calling a non-function as a function | Runtime | 'x is not a function' |
| ReferenceError | Accessing a variable that is not declared | Using an undeclared variable | Runtime | 'x is not defined' |
| SyntaxError | Code has invalid syntax | Missing a closing bracket or keyword | Parsing (before runtime) | 'Unexpected token' |
Key Differences
TypeError happens when you try to use a value in a way that doesn't match its type, like calling a number as if it were a function or accessing a property on null or undefined. This error only appears when the code runs and the invalid operation is attempted.
ReferenceError occurs when you try to use a variable that JavaScript doesn't know about because it was never declared or is out of scope. This also happens at runtime when the code tries to access that variable.
SyntaxError is different because it happens before the code runs. It means the code is not written correctly according to JavaScript rules, so the engine cannot even start running it. Examples include missing brackets, extra commas, or wrong keywords.
TypeError Code Example
const num = 5; num(); // Trying to call a number as a function
ReferenceError Equivalent
console.log(notDeclaredVar); // Accessing a variable that was never declared
When to Use Which
Choose TypeError to understand issues where values are used incorrectly by type during program execution. Use ReferenceError to catch mistakes where variables are missing or out of scope. SyntaxError indicates problems in your code structure that must be fixed before running the program.
In practice, fix SyntaxError first because your code won't run otherwise, then debug ReferenceError and TypeError as they appear during execution.