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.
[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.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!