How to generate AST(Abstract Syntax Tree) of javascript code?


Abstract Syntax Tree or AST is syntactic tree representations of a code. Each node of the tree denotes a construct occurring in the source code. This is a fundamental part of the way a compiler works. The syntax is “abstract” as it does not represent every detail appearing in the real syntax, but rather just the structural or content-related details. Abstract Syntax Tree does not include unnecessary punctuation and delimiters (braces, parentheses, semicolons, etc.).

Lets create a program to generate Abstract Syntax Tree.

First You need to install a third-party library named as Esprima by following command.

npm install esprima

Code to generate Asbstract Syntax Tree of Javascript Code is as follows:

var esprima = require('esprima');
// source code for which we have to generate AST
var program = 'const foo = 22';

let ast = esprima.parseScript(program);

Output of above code is:

% node demo.js
  "type": "Program",
  "body": [
      "type": "VariableDeclaration",
      "declarations": [
          "type": "VariableDeclarator",
          "id": {
            "type": "Identifier",
            "name": "foo"
          "init": {
            "type": "Literal",
            "value": 22,
            "raw": "22"
      "kind": "const"
  "sourceType": "script"

esprima.parseScript() takes complete source code as string and then generates abstract syntax tree of the code.


If you want to make static parser tool then Abstract Syntax Tree is very crucial. Hope you understand concept of AST. Lets create your own and have fun.

#Happy Coding #TopCode

#abstract syntax tree node.js #abstract syntax tree topcode #abstract syntax tree code #abstract syntax tree js #abstract syntax tree in compiler design #abstract syntax tree examples #abstract syntax tree examples in compiler design #abstract syntax tree in c #abstract syntax tree implementation c++ #abstract syntax tree algorithm #abstract syntax tree #use of abstract syntax tree #abstract syntax tree definition

, , , , ,

Related posts

Latest posts

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Please disable your adblocker or whitelist this site!

How to whitelist website on AdBlocker?

How to whitelist website on AdBlocker?

  1. 1 Click on the AdBlock Plus icon on the top right corner of your browser
  2. 2 Click on "Enabled on this site" from the AdBlock Plus option
  3. 3 Refresh the page and start browsing the site