Running Javascript code

So you've just written some Javascript code and you want to run it in your browser. How exactly does that work?

This is a topic that seems somewhat mysterious at first, particularly if you have never spent time with a low-level language like Assembly or C.

Today I watched video from Ariya Hidayat, the creator of popular JS libraries PhantomJS and Esprima, on Javascript Engines that was extremely informative about how Javascript code actually runs.

To summarize a few of his slides, he states that the Javascript engine (such as Google Chrome's V8) follows these steps: 
1. Tokenizes / scans the code - The characters in the code are identified as a keyword, an identifier (e.g. variable name), an operator, etc. 
2. Parses and creates an Abstract Syntax Tree (AST) - The AST forms the relationships between the various tokens. 
3. Serialize the AST and generate bytecode - Ariya mentions this as a common optimization that modern Javascript engines use as it's faster than having to traverse the AST normally. 
4. Just-In Time (JIT) compiled - At this point, the code is compiled into machine code right before you need to use it.

Ariya goes into greater detail on each of these steps and if you're interested in getting a detailed understanding of the inner-workings of Javascript, I recommend you to watch it.

There's a JSConf video by Martha Girdler called The Javascript Interpreter Interpreted that provides a gentler, and less detailed introduction to this topic.

views