What is JavaScript AST, how to play with it?

SpiderMonkey offers the parser api. This is probably the easiest way to get your hands on the syntax objects.

There's also open js-js parsers like Esprima (which is ECMAScript, really, but it's right up the alley)


Abstract Syntax Tree (AST), is a tree representation of program source code.

There is a couple JavaScript AST standards:

  • estree - standard for EcmaScript AST;
  • shift - was designed with transformation in mind, not compatible with estree;
  • babel - supports language features which is have not yet become a standard, but have a proposal.

Here is a list of JavaScript parsers:

  • esprima one of the first
  • acorn very popular, fast and stable
  • espree based on acorn, used in eslint;
  • @babel/parser based on acorn, supports all new language features
  • shfit-ast parser produces Shift AST
  • typescript can parse JavaScript and TypeScript, producing it's own AST format for this

You can find more parsers on astexplorer.net, most of them estree compatible.

While most parsers that supports estree can be easily replaced by each other, babel has very reach infrastructure needed for comfortable work with AST. It has:

  • handbook describing all the tools, and ways to use it.
  • @babel/traverse - maintains the overall tree state, and is responsible for replacing, removing, and adding nodes;
  • @babel/template - simplest way to create a AST-node from string.
  • @babel/types - contains builders and checkers of AST-nodes.

One of the simplest way to play with AST, is using putout, which is based on babel and supports simplified way of transforming JavaScript code with help of plugins API.

Here is example of removing DebuggerStatement node:

module.exports.replace = () => ({
    'debugger': '',
});

If you want switch places of variables, changing the way of declaration:

module.exports.replace = () => ({
    'let __a = __b': 'const __b = __a'
});

If you want transform this code into return x[0]:

for (const x of y) {
    return x;
}

You can use:

module.exports.replace = () => ({
    'for (const __a of __b) {return __a}': 'return __a[0]',
});

With help of putout you can make simplest transformation of JavaScript code without handling with AST directly.


1.You can take a look at AST explorer. An online tool to explore the ASTs generated by more than 10 parsers. It is a good tool to learn AST tree of a language.
AST explorer source at Github.com.

enter image description here


2.Also you can paste your js code into JavaScript AST visualizer and click "show ast" button, you will see the AST visully.

demo js code:

function foo(d) {
  d += 3;
    return d+999
}
function bar(d) {
    return d*100
}

js ast demo