Skip to content

/standards-javascript

This skill provides JavaScript coding standards and is automatically loaded for JavaScript projects. It includes modern ES2025 patterns, async handling, and recommended tooling.

From plugin
5711 skills12 commands1 hooks
shell
$ npx -y skills add b33eep/claude-code-setup --skill standards-javascript --agent claude-code

How it fires

How this skill gets triggered: by you, by Claude, or both.

  • Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.
  • You can call itInvoke it directly when you want it.
  • Slash command/standards-javascript
How auto-invocation works

Context preview

The summary Claude sees to decide when to auto-load this skill.

This skill provides JavaScript coding standards and is automatically loaded for JavaScript projects. It includes modern ES2025 patterns, async handling, and recommended tooling.

SKILL.md

standards-javascript.SKILL.md
name: standards-javascript
description: This skill provides JavaScript coding standards and is automatically loaded for JavaScript projects. It includes modern ES2025 patterns, async handling, and recommended tooling.
type: context
applies_to: [javascript, nodejs, express, fastify, hapi, npm, yarn, pnpm, bun, deno, vitest, jest, mocha]
file_extensions: [".js", ".mjs", ".cjs"]

JavaScript Coding Standards

Core Principles

1. **Simplicity**: Simple, understandable code 2. **Readability**: Readability over cleverness 3. **Maintainability**: Code that's easy to maintain 4. **Testability**: Code that's easy to test 5. **DRY**: Don't Repeat Yourself - but don't overdo it

General Rules

  • **Early Returns**: Use early returns to avoid nesting
  • **Descriptive Names**: Meaningful names for variables and functions
  • **Minimal Changes**: Only change relevant code parts
  • **No Over-Engineering**: No unnecessary complexity
  • **Minimal Comments**: Code should be self-explanatory. No redundant comments!
  • **Async/Await**: Always use async/await for async operations

Naming Conventions

| Element | Convention | Example | |---------|------------|---------| | Variables/Functions | camelCase | `getUserById`, `isActive` | | Classes | PascalCase | `UserService`, `ApiClient` | | Constants | UPPER_SNAKE_CASE | `MAX_RETRY_COUNT` | | Private | Prefix with `_` or `#` | `_internalMethod`, `#privateField` | | Files | kebab-case or camelCase | `user-service.js`, `userService.js` | | Event Handlers | Prefix with `handle` | `handleClick`, `handleSubmit` |

Project Structure

myproject/
├── src/
│   ├── index.js              # Entry point
│   ├── config.js             # Settings, env vars
│   ├── models/
│   │   └── user.js           # Domain models
│   ├── services/
│   │   └── user-service.js   # Business logic
│   ├── routes/
│   │   └── user-routes.js    # API routes
│   └── utils/
│       └── helpers.js        # Utility functions
├── tests/
│   ├── services/
│   │   └── user-service.test.js
│   └── setup.js
├── package.json
└── README.md

ES Modules (Preferred)

// math.js - Named exports
export function add(a, b) {
    return a + b;
}

export function multiply(a, b) {
    return a * b;
}

// app.js - Import
import { add, multiply } from './math.js';

// Default export
export default class UserService {
    // ...
}

// Import default
import UserService from './user-service.js';

**package.json for ES Modules:**

{
    "type": "module",
    "exports": {
        ".": "./src/index.js",
        "./utils": "./src/utils/index.js"
    }
}

Async/Await Patterns

// Always use async/await for async operations
async function fetchUserData(userId) {
    try {
        const response = await fetch(`https://api.example.com/users/${userId}`);

        if (!response.ok) {
            throw new Error(`API error: ${response.statusText}`);
        }

        return await response.json();
    } catch (error) {
        console.error('Fetch failed:', error);
        throw error;
    }
}

// Parallel execution with Promise.all
async function fetchMultipleUsers(userIds) {
    const users = await Promise.all(
        userIds.map(id => fetchUserData(id))
    );
    return users;
}

// Race with timeout
async function fetchWithTimeout(promise, timeout) {
    return Promise.race([
        promise,
        new Promise((_, reject) =>
            setTimeout(() => reject(new Error('Timeout')), timeout)
        ),
    ]);
}

// Get all results, including failures
async function fetchAllSettled(urls) {
    const results = await Promise.allSettled(
        urls.map(url => fetch(url).then(r => r.json()))
    );
    return results;
}

Best Practices

// Prefer const over let
const users = [];

// Use nullish coalescing and optional chaining
const name = user?.profile?.name ?? 'Anonymous';

// Prefer template literals
const message = `Hello, ${user.name}!`;

// Use destructuring
const { id, name, email } = user;
function processUser({ id, name }) { }

// Prefer array methods over loops
const activeUsers = users.filter(u => u.isActive);
const userNames = users.map(u => u.name);
const totalAge = users.reduce((sum, u) => sum + u.age, 0);

// Use Object.freeze for immutable constants
const CONFIG = Object.freeze({
    apiUrl: 'https://api.example.com',
    maxRetries: 3,
});

// Private class fields with #
class UserService {
    #apiClient;

    constructor(apiClient) {
        this.#apiClient = apiClient;
    }

    async getUser(id) {
        return this.#apiClient.get(`/users/${id}`);
    }
}

Express Framework

import express from 'express';

const app = express();
app.use(express.json());

// Routes
app.get('/users', (req, res) => {
    res.json([
        { id: 1, name: 'John' },
        { id: 2, name: 'Jane' },
    ]);
});

app.post('/users', (req, res) => {
    const { name } = req.body;
    res.status(201).json({ id: 3, name });
});

app.get('/users/:id', (req, res) => {
    const { id } = req.params;
    res.json({ id: parseInt(id), name: 'User' });
});

// Error handling middleware (must be last)
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({ error: 'Internal Server Error' });
});

app.listen(3000, () => {
    console.log('Server running on :3000');
});

**Middleware Pattern:**

// Logging middleware
const logger = (req, res, next) => {
    console.log(`${req.method} ${req.path}`);
    next();
};

// Authentication middleware
const authenticateToken = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    const token = authHeader?.split(' ')[1];

    if (!token) {
        return res.status(401).json({ error: 'Missing token' });
    }

    // Verify token...
    req.user = decodedUser;
    next();
};

app.use(logger);
app.use('/api/protected', authenticateToken);

Fastify Framework

import Fastify from 'fastify';

const
Read more
Read it on GitHub ↗

Showing the first part of this file.

Ships withclaude-code-setup

Persistent memory for Claude Code via Markdown files. 📖 Read the Documentation for detailed guides, tutorials, and reference.

Get the whole plugin, auto-invoked
Stats
57
Stars
0
Views
6
Forks
Maintained
Maintenance
Shell
Language
MIT
License
2mo ago
Last commit
6mo ago
Created

Repo: b33eep/claude-code-setup