DEV Community

Cover image for JavaScript Parser and Engine
Davinder
Davinder

Posted on • Originally published at devkamboj.in

JavaScript Parser and Engine

In this article, I will just very quickly tell you. How the JavaScript codes that we write is actually executed.

Originally posted at

So, JavaScript is always hosted in some environment. And that is most typically a browser such a Google Chrome, Firefox, Safari, etc. This is where JavaScript runs. There can also be other hosts such as the NodeJS web server, or even some applications that accept JavaScript code as input. However, I will just focus on the browser in this Article.

So when we write our JavaScript code and actually want to run it, there’s a lot of stuff happening behind the scenes. So what happens is that the host where JavaScript is hosted has some kind of JavaScript engine that takes our code and executes it. So in very simple terms, a JavaScript engine is a program that executes JavaScript code. There are many different engines out there, like

  1. Google’s V8 engine, that is used in Google Chrome.
  2. SpiderMonkey is Mozilla’s JavaScript engine
  3. JavaScriptCore and many more.

Now, the first thing that happens inside the engine, is that our code is parsed by a parser, which basically reads our code line by line, and checks if the syntax of the code that we gave it, is correct. So this means that the parser knows the JavaScript rules and how it has to be written in order to be correct, to be valid. And if you make some mistakes, it basically throws an error and stops the execution.

javascriptParser

If everything is correct though, then the parser produces a data structure known as the Abstract Syntax Tree, which is then translated into machine code. So this code is no longer JavaScript code, but a code, or let’s say a set of instructions, that can be executed directly by the computer’s processor. And it’s only when our code already converted to machine code, actually runs and does its work.

javascriptEngine1

I just want you to get the basic idea of what actually happens once we choose to run our code. And there is actually way more going on behind the scenes. And different engines do things in a slightly different way.

Top comments (0)