Javascript: Javascript Syntax Parser

Daniel Zhou
2 min readNov 1, 2017

--

Syntax parser is part of Javascript engine. It reads your code character by character, tells what your code does, and check if the grammar is correct or not.

You can think syntax parser as an interpreter between your code and computer. It translates your code to machine readable code. Javascript is flexible and fault-tolerant. That means syntax parser or the javascript engine works intelligently, and try best in guessing and understanding what you want. Sometimes it does what you expect, sometimes not.

Javascript is famous to its fault tolerance as opposed to static typing languages such as C# and Java. Here are some examples:

1. Hoisting -you can use a variable before its declaration.

2. In global environment, you can use a variable without even declaring it.

3. You can concat string with a number : 1 + ‘2’

4. You can use equality operator to compare object with primitive: Number(2) == 2

5. You can call a function, and pass no parameters.

and more …

C# or Java does not like all those wild stuff above. However, in Javascript, you sort of live in a more free world with fewer cops to check your code legitimacy.

However, sometimes, syntax parser goes a little bit far and does things you would not want in the first place. Here is a notorious one — automatic semicolon insertion.

In the code below, the key word ‘return’ takes the whole line. Javascript does not raise a red flag on it. Instead, it automatically insert a ‘; ‘ after the keyword ‘return’. When the function gets called, undefined is returned as the result.

For good practice, you should always remember to keep the key word ‘return’ and the return value in the same line.

In conclusion, our code is not directly executed by the computer, but via Javascript engine. Javascript engine sets up execution context and interprets our code with its best understanding, and does things we may be aware or not aware about.

--

--