Code Examples

Practical examples to help you get started with Esprima

Basic Variable Declaration

Parse a simple variable declaration and see the resulting AST structure.

const greeting = 'Hello, World!';

Function Declaration

Parse a function declaration with parameters and return statement.

function add(a, b) {
  return a + b;
}

Arrow Function

Parse modern ES6 arrow function syntax.

const multiply = (x, y) => x * y;

Conditional Statement

Parse if-else conditional logic.

if (temperature > 30) {
  console.log('Hot');
} else {
  console.log('Cold');
}

Loop Statement

Parse a for loop with initialization, condition, and increment.

for (let i = 0; i < 10; i++) {
  console.log(i);
}

Object Literal

Parse an object literal with properties and methods.

const person = {
  name: 'John',
  age: 30,
  greet() {
    return `Hello, ${this.name}`;
  }
};

Array Operations

Parse array creation and method chaining.

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);

Async/Await

Parse asynchronous function with async/await syntax.

async function fetchData() {
  const response = await fetch('/api/data');
  return await response.json();
}

Class Declaration

Parse ES6 class with constructor and methods.

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  area() {
    return this.width * this.height;
  }
}

Destructuring

Parse object and array destructuring patterns.

const { name, age } = user;
const [first, second, ...rest] = items;

Template Literals

Parse template literal strings with expressions.

const name = 'World';
const message = `Hello, ${name}!`;

Try-Catch Block

Parse error handling with try-catch-finally.

try {
  riskyOperation();
} catch (error) {
  console.error(error);
} finally {
  cleanup();
}

Real-World Use Cases

Code Linting

Use Esprima to build custom linting rules that enforce coding standards across your project. Parse code and analyze patterns to detect potential issues.

const ast = esprima.parseScript(code);
// Traverse AST to find patterns
// Flag violations of coding standards

Code Metrics

Calculate complexity metrics like cyclomatic complexity, lines of code, and function count by analyzing the AST structure.

function calculateComplexity(ast) {
  let complexity = 1;
  // Count decision points in AST
  return complexity;
}

Code Transformation

Transform JavaScript code by modifying the AST. Perfect for transpilers, code modernization, and automated refactoring tools.

const ast = esprima.parseScript(oldCode);
// Modify AST nodes
const newCode = generate(ast);

Documentation Generation

Extract function signatures, parameters, and JSDoc comments from source code to automatically generate API documentation.

function extractDocs(ast) {
  // Find function declarations
  // Extract comments and metadata
  return documentation;
}

Tips & Best Practices

💡

Enable Location Tracking

Use the loc option to track line and column numbers for better error reporting and source maps.

Parse Once, Analyze Many

Parsing is the expensive operation. Cache the AST and run multiple analyses on the same tree for better performance.

🔍

Handle Errors Gracefully

Always wrap parsing in try-catch blocks. Use the tolerant option if you need to continue after errors.

📦

Use Visitor Patterns

Implement visitor patterns to traverse the AST efficiently. Libraries like estraverse can help with tree walking.

Ready to Start Parsing?

Try these examples in our interactive parser or dive into the documentation.