is-identifier

1.0.1 · active · verified Sun Apr 19

The `is-identifier` package provides a highly focused utility to determine if a given string constitutes a valid JavaScript identifier according to ECMAScript specifications. Currently at stable version 1.0.1, this package follows Sindre Sorhus's typical release cadence of infrequent, targeted updates, primarily for bug fixes or minor spec clarifications, ensuring long-term stability. Its key differentiators include precise adherence to the JavaScript identifier rules, including reserved keywords (like `await`) and special global properties (like `globalThis`, `Infinity`, `NaN`, `undefined`) which it correctly treats as invalid identifiers for practical use, despite some not being strictly "keywords". It is a small, dependency-free module optimized for performant identifier validation, contrasting with broader AST parsing libraries.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and use `isIdentifier` to check various strings for JavaScript identifier validity, including valid cases, invalid cases, reserved keywords, and special global properties treated as non-identifiers.

import isIdentifier from 'is-identifier';

// Basic valid identifiers
console.log(`'foo' is identifier: ${isIdentifier('foo')}`);
console.log(`'$bar' is identifier: ${isIdentifier('$bar')}`);
console.log(`'_baz' is identifier: ${isIdentifier('_baz')}`);
console.log(`'myVariable123' is identifier: ${isIdentifier('myVariable123')}`);

// Invalid identifiers
console.log(`'1kg' is identifier: ${isIdentifier('1kg')}`);
console.log(`'await' is identifier: ${isIdentifier('await')}`); // Reserved keyword
console.log(`'my-variable' is identifier: ${isIdentifier('my-variable')}`);
console.log(`'function' is identifier: ${isIdentifier('function')}`); // Reserved keyword

// Special global properties treated as non-identifiers
console.log(`'globalThis' is identifier: ${isIdentifier('globalThis')}`);
console.log(`'Infinity' is identifier: ${isIdentifier('Infinity')}`);
console.log(`'NaN' is identifier: ${isIdentifier('NaN')}`);
console.log(`'undefined' is identifier: ${isIdentifier('undefined')}`);

view raw JSON →