Compiled vs Interpreted
Finally, as we can see in the illustration, during the compile-time also happens something called “parsing”, a process that is in charge of “analyzing and converting a program into an internal format that a runtime environment can actually run” (MDN Docs, 2021), or in other words, this is the translation from the thing we have, into the thing we need to make it work in the browser. Knowing about the step of parsing during the compilation is necessary for you to understand the exact part of the execution that deals with the missing semicolons.
Automatic Semicolon Insertion (ASI)
Now that we know about the relationship between the compiling process, the parsing, and the interpretation of the code in the browser, we are ready to talk about something that happens during the parsing step called Automatic Semicolon Insertion (ASI).
- Empty statement
- Variable statement
- Import & export
- Expression statements
- Continue, break, throw & return
To clarify this idea a little bit more we can take a look at the next illustration with a few simple lines where we can see the before and after the ASI in our code:
- When there is a line terminator that is not allowed.
- When the parser cannot parse the next line.
- When we have ++, –, continue, break, return, yield, yield* and module.
Again, as we can see on the documentation (ECMAScript, 2021) this is a simple way to represent and understand when the ASI works and when it does not:
But, if you’re still not sure about how true this is, you can reproduce it yourself on the browser’s console like this:
Only the first one didn’t work because of the missing semicolon that the ASI couldn’t add, but the same code with a line terminator (the code on the new line) did work because the ASI was able to fix it.
When to use semicolons
In this case, the missing semicolon on the declaration of variable c breaks the following toString function because its value is recognized as a non declared function. We can fix this error with a semicolon in the declaration of the last variable. (Flavio Copes, 2018)
With that being said, we’re trying to use a variable that doesn’t exist yet, and again, the way to fix this behavior is with the almighty semicolon.