I was doing a bit of research on interpreted v/s compiled. Found this article which states…
console.log("Hello World");
oops oops;
This code won’t output Hello World because JS is compiled and because of oops oops; JS compiler will throw an error which it surely does. SyntaxError: Unexpected identifier
But if I remove the second oops i.e.
console.log("Hello World");
oops;
This code still throws an error, albeit a different error ReferenceError: oops is not defined, but it first writes Hello World to the console.
I understand both the errors. So, when there’s a Syntax Error, the compilation process stops because it cannot process wrong syntax and cannot produce an AST (Abstract Syntax Tree) from what I understand. Hence, no byte code. But when it’s a Reference Error, how can it compile?
Sorry if I’m asking this question on the wrong exchange. If so, just let me know the correct forum where I should be asking this question.
Also, I know it’s unexpected behaviour, and I shouldn’t be asking why broken code acts the way it does. I’m just curious.
>Solution :
First step is tokenization/scanning/lexing:
console.log("Hello World");
oops oops;
is "split" into
console . log ( "Hello World" ) ; oops oops ;
Then comes the parser (which validates/parses a stream of tokens into a tree).
It sees this as a statement (a function call):
console . log ( "Hello World" ) ;
Then it sees this:
oops oops;
Which is invalid syntax, and therefore you have a syntax error.
In your second example, this is only:
oops;
Which is valid syntax.
Next after this tree of some sort is made, there’s JIT and a bunch of other steps, but we are only interested in execution.
It executes console.log perfectly fine, but then it sees that there’s an identifier that isn’t defined. Hence the reference error.
So in summary, JavaScript is interpreted, (just-in-time compiled too), and because it’s interpreted, it interprets your code "line-by-line". It interprets and executes console.log, then attempts to interpret and execute oops;, which results in an error.