What is a syntax parser?

"A program that reads your code and determines what it does and if its grammar is valid" - Anthony Alicea

The syntax parser is part of the JavaScript engine, along with the compiler and interpreter. The engine reads your code and determines how the computer will execute that code. You never give instructions to the computer directly, the engine acts as the middleman.

It's important to know how the parser works so you know how your code will be read.

Return statements

One of the cool things about the JavaScript parser is that you don't need to add a semicolon after each expression. If you leave it out, the parser will automatically insert it for you. This has some unintended consequences. Take this code example:

index.js
1
constgreeting=()=>{
2
return
3
'Hello';
4
}
5
6
constprintGreeting=greeting();
7
console.log(printGreeting)
8
//undefined
9
10
constgreeting=()=>{
11
return'Hello';
12
}
13
14
constprintGreeting=greeting();
15
console.log(printGreeting)
16
//Hello
17

At line 2, the parser will add a semicolon ; directly after the return keyword.

This means the parser has interpreted the code to read return;, which means to return nothing.

For this reason, you should remember to keep the return keyword and the return value on the same line.

Further reading

Javascript Syntax Parser