is-expression

4.0.0 · active · verified Sun Apr 19

The `is-expression` package provides a utility function for synchronously validating if a given string is a syntactically correct JavaScript expression. It is currently at version 4.0.0 and appears to have an infrequent release cadence, with the latest major update focusing on parser upgrades. The library uses Acorn under the hood to perform its parsing, allowing for detailed error reporting when the `throw` option is enabled. Key differentiators include its simplicity, direct integration with Acorn options, and the ability to toggle strict mode or allow line comments, making it suitable for environments like templating engines (e.g., Pug) or dynamic code evaluation where robust expression validation is crucial. It focuses purely on syntax, not semantic validity or runtime behavior.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic expression validation using `isExpression` and how to leverage `throw`, `strict`, and `lineComment` options to control parsing behavior and error handling.

import { isExpression } from 'is-expression';

// Basic validation
console.log(isExpression('myVar')); // => true
console.log(isExpression('var'));   // => false (keyword, not expression)
console.log(isExpression('["an", "array"].indexOf("index")')); // => true

// Using options: throw on error
try {
  isExpression('const foo', { throw: true }); // 'const' is a declaration, not an expression
} catch (error) {
  console.error('Caught expected error:', error.message); // SyntaxError: Unexpected token 'const' (1:0)
}

// Using options: strict mode
console.log(isExpression('public')); // => true (in non-strict mode)
console.log(isExpression('public', { strict: true })); // => false (in strict mode, 'public' is a reserved keyword)

// Using options: allowing comments
console.log(isExpression('abc // my comment')); // => false (comments not allowed by default)
console.log(isExpression('abc // my comment', { lineComment: true })); // => true

view raw JSON →