0
0
JavascriptComparisonBeginner · 3 min read

TypeError vs ReferenceError vs SyntaxError in JavaScript: Key Differences

In JavaScript, a 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 TypeWhen It OccursExample CauseWhen DetectedCommon Message
TypeErrorUsing a value in an invalid way for its typeCalling a non-function as a functionRuntime'x is not a function'
ReferenceErrorAccessing a variable that is not declaredUsing an undeclared variableRuntime'x is not defined'
SyntaxErrorCode has invalid syntaxMissing a closing bracket or keywordParsing (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

javascript
const num = 5;
num(); // Trying to call a number as a function
Output
TypeError: num is not a function
↔️

ReferenceError Equivalent

javascript
console.log(notDeclaredVar); // Accessing a variable that was never declared
Output
ReferenceError: notDeclaredVar is not defined
🎯

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.

Key Takeaways

SyntaxError means your code has invalid syntax and stops execution before running.
ReferenceError happens when you use a variable that is not declared or out of scope.
TypeError occurs when you use a value in a way that doesn't match its type during runtime.
Fix SyntaxErrors first, then debug ReferenceErrors and TypeErrors as they appear.
Understanding these errors helps you write and debug JavaScript code more effectively.