Chapter 2. Syntactic Analysis (Parsing)

The main use case of Esprima is to parse a JavaScript program. This is also known as syntactic analysis.

Esprima parser takes a string representing a valid JavaScript program and produces a syntax tree, an ordered tree that describes the syntactic structure of the program. The resulting syntax tree is useful for various purposes, from program transformation to static program analysis.

The interface of the parse function is as follows:

  1. esprima.parse(input, config, delegate)

where

  • input is the string representing the program to be parsed
  • config is an object used to customize the parsing behavior (optional)
  • delegate is a callback function invoked for every single node (optional)

The input argument is mandatory. Its type must be a string, otherwise the parsing behavior is not determined. The other two arguments, config and delegate, are optional.

The object returned by the parse function is the syntax tree, following the format described in details in Appendix A. Syntax Tree Format.

The description of various parsing configuration is summarized in the following table:

NameTypeDefaultDescription
sourceTypeString“script”Define the program type: a script or a module
jsxBooleanfalseSupport JSX syntax
rangeBooleanfalseAnnotate each node with its index-based location
locBooleanfalseAnnotate each node with its column and row-based location
tolerantBooleanfalseTolerate a few cases of syntax errors
tokensBooleanfalseCollect every token
commentBooleanfalseCollect every line and block comment

Runkit with Esprima parse

The previous chapter, Getting Started, already demonstrates the simplest possible example of using Esprima parser. To use it as the basis for further experiments, use Runkit and tweak the existing demo notebook: runkit.com/ariya/esprima-parse-demo.