This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    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.

    javascriptJavaScript
    Code

    Code

    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
    Transcript

    Transcript

    00:00 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.

    00:24 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.

    00:50 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.

    01:09 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.

    01:36 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.

    Discuss

    Discuss