Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Introduction to Abstract Syntax Trees

    Kent C. DoddsKent C. Dodds

    In this lesson, we’ll learn about the key technology used by JavaScript engines and tools like ESLint and Babel to run, lint, and modify your source code. The JavaScript Abstract Syntax Tree (or AST for short) is a JSON representation of your code that is represented by a tree structure. In this lesson we’ll explore that tree structure to get a feel for how code translates to an AST.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    An abstract syntax tree, or AST, is an object representation of our code. This object is a tree structure, just like the document object model, or DOM. The AST is generated by a tool called a parser. This tool here by Rapid uses the Esprima parser and allows us to visualize the AST of the code that we type in here.

    If we type far a=3 and click "Show AST," we can see that the abstract syntax tree represented here in the chart. A tree structure consists of nodes with properties, which can have parent and child nodes. Each of these boxes represent a node in our AST. We can see what part of our code each represents by hovering over them.

    We start out with our program that represents the whole file. Then we see our variable declaration as a child node of our program, which has a variable declarator of a=3. Finally we see the identifier a and the literal 3 as child nodes of the variable declarator.

    Let's change our code slightly and see how that affects our AST. We'll add b=4 and then click Show AST again. Now we see that the variable declaration has two children, one for each variable declarator. Now we'll change the assignment to b to be a+4. Click Show AST and now we'll see a whole new node that represents a binary expression.

    This has two child nodes, for the left and right side of our binary expression. Let's paste in some more complicated code here and click Show AST. Now we'll see that the AST grows to have many different node types and relationships to represent each bit of our code.