JavaScript Idioms and Patterns
Modern JavaScript (ES2024+) rewards modules, async/await, and functional patterns. Idiomatic JS = strict mode, modular, well-tested.
Scope: Plain JavaScript only — projects with no tsconfig.json. This skill is intentionally thin: most JS guidance (coercion traps, async pitfalls, scope bugs, security, collections, performance) is shared with TypeScript and lives in one place to avoid divergence.
Loading guards:
- If
tsconfig.json exists, do NOT load this skill — load @.agents/skills/typescript-idioms/SKILL.md instead. TypeScript is preferred whenever available.
- Coercion / async / scope / security / collection / performance pitfalls: see
@.agents/skills/typescript-idioms/references/ts-patterns-and-anti-patterns.md — despite the filename, it is scoped to "TypeScript/JavaScript" and covers runtime pitfalls that apply to plain JS verbatim.
- Project layout: see
@.agents/skills/typescript-idioms/references/project-structure.md (the generic backend/library/monorepo layouts are language-level, not TS-only).
Module System
- ES modules over CommonJS for all new code:
// ✅ ESM
import { createTask } from './task-service.js';
export function handler(req, res) { ... }
// ❌ CommonJS (legacy only)
const { createTask } = require('./task-service');
- Always use
.js extensions in ESM relative imports — Node.js ESM requires them; bundlers accept them.
package.json "type": "module" to enable ESM by default; use .cjs for any CommonJS holdouts.
- CJS/ESM interop —
import default from './cjs.cjs' works; named exports from CJS are not statically analyzable, prefer module.exports = { named } + const { named } = require(...) or migrate to ESM.
Declarations and Strict Mode
const by default, let when reassignment needed, never var. (var hoisting/closure bugs: see ts-patterns-and-anti-patterns.md §3.)
- Enable strict mode —
'use strict'; at file top in scripts. Strict mode is implicit in ESM modules ("type": "module" in package.json) and class bodies.
- Optional chaining and nullish coalescing (prefer
?? over || to avoid 0/'' falsy traps):const title = task?.title ?? 'Untitled';
const count = config?.scoring?.default ?? 0;
- Destructuring with defaults for clean parameter handling:
function createTask({ title, priority = 'medium', tags = [] }) { ... }
Runtime Without Types
Since there is no compiler to catch mistakes, lean harder on:
- Runtime validation at boundaries — use Zod (works in plain JS) or
ajv to validate external input. Don't trust unvalidated I/O.
- Defensive narrowing —
typeof, Array.isArray(), Object.hasOwn() checks before property access. (Coercion traps: see ts-patterns-and-anti-patterns.md §1.)
- JSDoc for public APIs —
@param, @returns, @throws give editors and tools type hints without a TS toolchain.
structuredClone() for deep copies (not JSON.parse(JSON.stringify())) — lossy and throws on cycles).
Error Handling
For universal error handling principles, see @.agents/rules/error-handling-principles.md. Below: JS-specific only.
- Domain error classes (never throw primitives — loses stack trace):
class DomainError extends Error {
constructor(message) { super(message); this.name = this.constructor.name; }
}
class NotFoundError extends DomainError {
constructor(resource, id) {
super(`${resource} '${id}' not found`);
this.resource = resource;
this.resourceId = id;
}
}
- Never
catch without handling. Empty catch blocks are forbidden.
- Always handle promise rejections — never floating/unhandled (see
ts-patterns-and-anti-patterns.md §2 for the full async pitfall catalog).
Naming
- camelCase for functions, variables. PascalCase for classes.
- UPPER_SNAKE_CASE for constants.
- Prefix booleans:
isActive, hasPermission, canEdit.
Testing
Vitest (preferred — ESM-native, zero-config) or Jest. Testing Library for DOM. (TypeScript skill mandates Vitest; in plain JS either is acceptable but Vitest is recommended.)
Toolchain and Formatting
| Tool |
Purpose |
Command |
| Prettier |
Formatting |
npx prettier --write . |
| ESLint |
Linting |
npx eslint . |
npm audit / pnpm audit |
CVE scanning |
npm audit |
Default package manager: pnpm (matches the TypeScript skill). Use npm only if the project already has a package-lock.json.
Related
- TypeScript Idioms @.agents/skills/typescript-idioms/SKILL.md (load this instead if tsconfig.json exists)
- TS/JS Patterns & Anti-Patterns @.agents/skills/typescript-idioms/references/ts-patterns-and-anti-patterns.md (shared coercion/async/scope/security pitfalls)
- Code Idioms and Conventions @.agents/rules/code-idioms-and-conventions.md
- Testing Strategy @.agents/rules/testing-strategy.md
- Error Handling Principles @.agents/rules/error-handling-principles.md
1---2name: javascript-idioms-23description: Plain JavaScript (ES2024+) idioms — ESM, CJS interop, runtime patterns without types. Use ONLY when TypeScript is unavailable; for TS load typescript-idioms.4---56## JavaScript Idioms and Patterns78Modern JavaScript (ES2024+) rewards modules, async/await, and functional patterns. Idiomatic JS = strict mode, modular, well-tested.910> **Scope:** Plain JavaScript only — projects with **no `tsconfig.json`**. This skill is intentionally thin: most JS guidance (coercion traps, async pitfalls, scope bugs, security, collections, performance) is shared with TypeScript and lives in **one place** to avoid divergence.11>12> **Loading guards:**13> - **If `tsconfig.json` exists, do NOT load this skill** — load `@.agents/skills/typescript-idioms/SKILL.md` instead. TypeScript is preferred whenever available.14> - **Coercion / async / scope / security / collection / performance pitfalls:** see `@.agents/skills/typescript-idioms/references/ts-patterns-and-anti-patterns.md` — despite the filename, it is scoped to "TypeScript/JavaScript" and covers runtime pitfalls that apply to plain JS verbatim.15> - **Project layout:** see `@.agents/skills/typescript-idioms/references/project-structure.md` (the generic backend/library/monorepo layouts are language-level, not TS-only).1617### Module System18191. **ES modules over CommonJS for all new code:**20 ```javascript21 // ✅ ESM22 import { createTask } from './task-service.js';23 export function handler(req, res) { ... }2425 // ❌ CommonJS (legacy only)26 const { createTask } = require('./task-service');27 ```282. **Always use `.js` extensions in ESM relative imports** — Node.js ESM requires them; bundlers accept them.293. **`package.json` `"type": "module"`** to enable ESM by default; use `.cjs` for any CommonJS holdouts.304. **CJS/ESM interop** — `import default from './cjs.cjs'` works; named exports from CJS are not statically analyzable, prefer `module.exports = { named }` + `const { named } = require(...)` or migrate to ESM.3132### Declarations and Strict Mode33341. **`const` by default, `let` when reassignment needed, never `var`.** (`var` hoisting/closure bugs: see `ts-patterns-and-anti-patterns.md` §3.)352. **Enable strict mode** — `'use strict';` at file top in scripts. Strict mode is implicit in ESM modules (`"type": "module"` in `package.json`) and class bodies.363. **Optional chaining and nullish coalescing** (prefer `??` over `||` to avoid `0`/`''` falsy traps):37 ```javascript38 const title = task?.title ?? 'Untitled';39 const count = config?.scoring?.default ?? 0;40 ```414. **Destructuring with defaults** for clean parameter handling:42 ```javascript43 function createTask({ title, priority = 'medium', tags = [] }) { ... }44 ```4546### Runtime Without Types4748Since there is no compiler to catch mistakes, lean harder on:491. **Runtime validation at boundaries** — use Zod (works in plain JS) or `ajv` to validate external input. Don't trust unvalidated I/O.502. **Defensive narrowing** — `typeof`, `Array.isArray()`, `Object.hasOwn()` checks before property access. (Coercion traps: see `ts-patterns-and-anti-patterns.md` §1.)513. **JSDoc for public APIs** — `@param`, `@returns`, `@throws` give editors and tools type hints without a TS toolchain.524. **`structuredClone()`** for deep copies (not `JSON.parse(JSON.stringify()))` — lossy and throws on cycles).5354### Error Handling5556> For universal error handling principles, see `@.agents/rules/error-handling-principles.md`. Below: JS-specific only.57581. **Domain error classes** (never throw primitives — loses stack trace):59 ```javascript60 class DomainError extends Error {61 constructor(message) { super(message); this.name = this.constructor.name; }62 }63 class NotFoundError extends DomainError {64 constructor(resource, id) {65 super(`${resource} '${id}' not found`);66 this.resource = resource;67 this.resourceId = id;68 }69 }70 ```712. **Never `catch` without handling.** Empty catch blocks are forbidden.723. **Always handle promise rejections** — never floating/unhandled (see `ts-patterns-and-anti-patterns.md` §2 for the full async pitfall catalog).7374### Naming75761. **camelCase** for functions, variables. **PascalCase** for classes.772. **UPPER_SNAKE_CASE** for constants.783. **Prefix booleans**: `isActive`, `hasPermission`, `canEdit`.7980### Testing8182**Vitest** (preferred — ESM-native, zero-config) or Jest. Testing Library for DOM. (TypeScript skill mandates Vitest; in plain JS either is acceptable but Vitest is recommended.)8384### Toolchain and Formatting8586| Tool | Purpose | Command |87|---|---|---|88| Prettier | Formatting | `npx prettier --write .` |89| ESLint | Linting | `npx eslint .` |90| `npm audit` / `pnpm audit` | CVE scanning | `npm audit` |9192> **Default package manager: `pnpm`** (matches the TypeScript skill). Use `npm` only if the project already has a `package-lock.json`.9394### Related95- TypeScript Idioms @.agents/skills/typescript-idioms/SKILL.md (load this instead if tsconfig.json exists)96- TS/JS Patterns & Anti-Patterns @.agents/skills/typescript-idioms/references/ts-patterns-and-anti-patterns.md (shared coercion/async/scope/security pitfalls)97- Code Idioms and Conventions @.agents/rules/code-idioms-and-conventions.md98- Testing Strategy @.agents/rules/testing-strategy.md99- Error Handling Principles @.agents/rules/error-handling-principles.md