Get Assigned Identifiers

1.2.0 · maintenance · verified Sun Apr 19

The `get-assigned-identifiers` package provides a focused utility for JavaScript AST analysis, specifically designed to extract identifiers that are initialized by a given AST node, including those within destructuring assignments. It helps developers programmatically understand which variables are being declared or assigned in a specific scope, a common requirement for static analysis tools, code linters, and refactoring utilities. The current stable version is 1.2.0, which was published over six years ago, indicating a mature but infrequently updated library. Its primary differentiator is its single-purpose API, which allows for direct integration without the overhead of larger AST manipulation frameworks. While stable for its intended use cases, users should be aware of its age when integrating with very recent JavaScript syntax or modern AST parsers, as compatibility might not be actively maintained.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to parse JavaScript code using Acorn and then extract assigned identifiers from various AST node types, including object and array destructuring, and simple variable declarations.

import { parse } from 'acorn';
import getAssignedIdentifiers from 'get-assigned-identifiers';

const code = `
  const { a, b: [ c,, ...x ], d = 10 } = someComplexObject();
  let [ e, f ] = otherArray;
  var g = 'hello';
`;

try {
  const ast = parse(code, { ecmaVersion: 2020 });
  
  // Example 1: Destructuring declaration
  const node1 = ast.body[0].declarations[0].id; // { a, b: [ c,, ...x ], d = 10 }
  console.log('Identifiers from destructuring:', getAssignedIdentifiers(node1));
  // Expected: [{ name: 'a' }, { name: 'c' }, { name: 'x' }, { name: 'd' }]

  // Example 2: Array destructuring
  const node2 = ast.body[1].declarations[0].id; // [ e, f ]
  console.log('Identifiers from array destructuring:', getAssignedIdentifiers(node2));
  // Expected: [{ name: 'e' }, { name: 'f' }]

  // Example 3: Simple variable declaration
  const node3 = ast.body[2].declarations[0].id; // g
  console.log('Identifiers from simple declaration:', getAssignedIdentifiers(node3));
  // Expected: [{ name: 'g' }]

} catch (error) {
  console.error('Error parsing code:', error.message);
}

view raw JSON →