Syntax error VS runtime error
1. What a syntax error is
A syntax error (SyntaxError) is an error that occurs before the program even starts running, when JavaScript cannot parse the code because the language's syntax rules are violated.
Simply put: the code cannot even begin to run.
Examples of syntax errors
if (true { // missing parenthesis
console.log("ok");
}function() { // a function without a name
console.log("hi");
}const a = ; // no value after "="The interpreter detects such errors at the parsing stage (before execution), so the code does not run at all.
An example with an explanation
console.log("before the error");
eval("let x = ;"); // SyntaxError
console.log("after the error"); // will not runThe error occurs immediately when trying to interpret the string, so the program never reaches the second console.log.
2. What a runtime error is
A runtime error is an error that occurs while the program is running, after the code has already passed syntax checking successfully.
That is, the syntax is correct, but the program's logic leads to a failure during execution.
Examples of runtime errors
console.log(a); // ReferenceError: a is not definedlet obj = null;
obj.name; // TypeError: Cannot read properties of nullJSON.parse("invalid JSON"); // SyntaxError, but raised during executionIn these cases the code runs, but breaks at a specific line during execution.
3. The main difference
| Criterion | Syntax error | Runtime error |
|---|---|---|
| When it occurs | At the parsing stage (before the code runs) | While the program is running |
Can it be caught with try...catch | No (the code will not even start) | Yes, it can be handled |
| Example | if (true { | console.log(a) |
| JS reaction | The code does not run at all | Execution stops at the error |
| Error type | SyntaxError | ReferenceError, TypeError, RangeError, etc. |
4. An example for a clear comparison
// Syntax error:
try {
eval("if (true { console.log('hi') }"); // <-- invalid syntax
} catch (e) {
console.log("Caught?", e.message);
}
// → this code will not even run, because the error occurs before execution
// Runtime error:
try {
console.log(a); // ReferenceError
} catch (e) {
console.log("Caught:", e.message);
}Summary
| Term | What it means |
|---|---|
| SyntaxError | An error in the code's structure - JS cannot interpret it |
| Runtime Error | An error while running syntactically correct code |
| Difference | The first happens at the parsing stage, the second at the execution stage |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.