JavaScript Idioms and Patterns
Modern JavaScript (ES2024+) rewards modules, async/await, and functional patterns. Idiomatic JS = strict mode, modular, well-tested. When TypeScript is available, prefer it — see typescript-idioms.
Scope: Plain JavaScript idioms. For TypeScript-specific patterns, load
@.gemini/skills/typescript-idioms/SKILL.md.
Modern Features
ES modules over CommonJS:
// ✅ ESM import { createTask } from './task-service.js'; export function handler(req, res) { ... } // ❌ CommonJS (legacy) const { createTask } = require('./task-service');constby default,letwhen reassignment needed, nevervar.Optional chaining and nullish coalescing:
const title = task?.title ?? 'Untitled'; const score = config?.scoring?.default ?? 0;Destructuring for clean parameter handling:
function createTask({ title, priority = 'medium', tags = [] }) { ... }structuredClonefor deep copies (notJSON.parse(JSON.stringify())).
Async/Await
async/awaitover raw promises:// ✅ const user = await fetchUser(id); const tasks = await fetchTasks(user.id); // ❌ Promise chains for sequential ops fetchUser(id).then(user => fetchTasks(user.id)).then(tasks => ...);Promise.allfor parallel I/O:const [user, tasks] = await Promise.all([fetchUser(id), fetchTasks(id)]);Always handle promise rejections — never unhandled.
Error Handling
Domain error classes:
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
catchwithout handling. Empty catch blocks are forbidden.
Naming
- camelCase for functions, variables. PascalCase for classes.
- UPPER_SNAKE_CASE for constants.
- Prefix booleans:
isActive,hasPermission,canEdit.
Testing
Vitest or Jest. Testing Library for DOM.
Formatting and Static Analysis
| Tool | Purpose | Command |
|---|---|---|
| Prettier | Formatting | npx prettier --write . |
| ESLint | Linting | npx eslint . |
npm audit |
CVE scanning | npm audit |
Related
- TypeScript Idioms @.gemini/skills/typescript-idioms/SKILL.md
- Code Idioms and Conventions GEMINI.md § Code Idioms and Conventions
- Testing Strategy GEMINI.md § Testing Strategy