Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 1083 of the free egghead.io lessons, plus get JavaScript content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Introduction to Abstract Syntax Trees

1:54 JavaScript lesson by

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.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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.

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?