DEV Community

daichitt
daichitt

Posted on

Abstract Syntax Tree with Javascript

Javascript sample code

const war = 5; // VariableDeclarator

 function triple(number){  // FunctionDeclaration
   return 3 * war; 
 }

Enter fullscreen mode Exit fullscreen mode

Json out put

{
  "type": "Program",
  "start": 0,
  "end": 59,
  "body": [
    {
      "type": "VariableDeclaration",
      "start": 0,
      "end": 14,
      "declarations": [
        {
          "type": "VariableDeclarator",
          "start": 6,
          "end": 13,
          "id": {
            "type": "Identifier",
            "start": 6,
            "end": 9,
            "name": "war"
          },
          "init": {
            "type": "Literal",
            "start": 12,
            "end": 13,
            "value": 5,
            "raw": "5"
          }
        }
      ],
      "kind": "const"
    },
    {
      "type": "FunctionDeclaration",
      "start": 16,
      "end": 59,
      "id": {
        "type": "Identifier",
        "start": 25,
        "end": 31,
        "name": "triple"
      },
      "expression": false,
      "generator": false,
      "async": false,
      "params": [
        {
          "type": "Identifier",
          "start": 32,
          "end": 38,
          "name": "number"
        }
      ],
      "body": {
        "type": "BlockStatement",
        "start": 39,
        "end": 59,
        "body": [
          {
            "type": "ReturnStatement",
            "start": 42,
            "end": 57,
            "argument": {
              "type": "BinaryExpression",
              "start": 49,
              "end": 56,
              "left": {
                "type": "Literal",
                "start": 49,
                "end": 50,
                "value": 3,
                "raw": "3"
              },
              "operator": "*",
              "right": {
                "type": "Identifier",
                "start": 53,
                "end": 56,
                "name": "war"
              }
            }
          }
        ]
      }
    }
  ],
  "sourceType": "module"
}

Enter fullscreen mode Exit fullscreen mode

Screenshot 2025-06-14 at 14.17.49.png

Reference

Javascript sample code

https://astexplorer.net/

https://www.youtube.com/watch?v=N5hczoxUzMU&list=LL&index=4&t=32s

https://www.npmjs.com/package/abstract-syntax-tree

Top comments (0)