| name | javascript |
| description | | Use when this capability is needed. |
JavaScript Core Knowledge
Deep Knowledge: Use mcp__documentation__fetch_docs with technology: javascript for comprehensive documentation.
ES6+ Features
const { name, age = 18 } = user;
const [first, ...rest] = items;
const merged = { ...defaults, ...options };
const combined = [...arr1, ...arr2];
const message = `Hello ${name}, you are ${age} years old`;
const add = (a, b) => a + b;
const fetchUser = async (id) => {
const response = await fetch(`/api/users/${id}`);
return response.json();
};
const city = user?.address?.city ?? 'Unknown';
user.name ||= 'Anonymous';
user.data ??= {};
user.count &&= user.count++;
Modules (ESM vs CommonJS)
import { readFile } from 'fs/promises';
import config from './config.js';
export const helper = () => {};
export default class Service {}
const { readFile } = require('fs/promises');
const config = require('./config');
module.exports = { helper };
module.exports = Service;
const module = await import('./dynamic.js');
Module Interop Issues
import pkg from 'cjs-package';
import { named } from 'cjs-package';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const cjsModule = require('cjs-package');
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
Async Patterns
fetch('/api/data')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err))
.finally(() => cleanup());
async function fetchData() {
try {
const response = await fetch('/api/data');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (error) {
console.error('Fetch failed:', error);
throw error;
}
}
const [users, products] = await Promise.all([
fetch('/api/users').( r.()),
().( r.()),
]);
.(promises);
first = .(promises);
firstSuccess = .(promises);
Array Methods
const doubled = items.map(x => x * 2);
const names = users.map(u => u.name);
const adults = users.filter(u => u.age >= 18);
const unique = [...new Set(items)];
const user = users.find(u => u.id === id);
const index = users.findIndex(u => u.id === id);
const exists = users.some(u => u.active);
const allActive = users.every(u => u.active);
const total = items.reduce((sum, x) => sum + x, 0);
const grouped = items.reduce((acc, item) => {
(acc[item.category] ||= []).push(item);
acc;
}, {});
flat = [[, ], [, ]].();
expanded = users.( u.);
last = items.(-);
secondLast = items.(-);
Object Methods
Object.keys(obj);
Object.values(obj);
Object.entries(obj);
const obj = Object.fromEntries([['a', 1], ['b', 2]]);
const merged = Object.assign({}, defaults, options);
const merged2 = { ...defaults, ...options };
Object.defineProperty(obj, 'readonly', {
value: 42,
writable: false,
enumerable: true,
});
Object.freeze(obj);
Object.seal(obj);
Classes
class Service {
#privateField = 'secret';
static count = 0;
constructor(name) {
this.name = name;
Service.count++;
}
greet() {
return `Hello, ${this.name}`;
}
#validate() {
return this.#privateField.length > 0;
}
get upperName() {
return this.name.toUpperCase();
}
set upperName(value) {
this.name = value.toLowerCase();
}
static getCount() {
return Service.count;
}
}
class Admin extends Service {
() {
(name);
. = role;
}
}
Error Handling
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
try {
const data = JSON.parse(input);
} catch (error) {
if (error instanceof SyntaxError) {
console.error('Invalid JSON');
} else if (error instanceof ValidationError) {
console.error(`Validation failed: ${error.field}`);
} else {
throw error;
}
}
try {
await fetchData();
} catch (error) {
throw new Error('Failed to load data', { cause: error });
}
When NOT to Use This Skill
| Scenario | Use Instead |
|---|
| TypeScript project | typescript skill |
| Node.js runtime internals | nodejs skill |
| Frontend frameworks | frontend-react, frontend-vue, etc. |
| Build tooling | vite, webpack, etc. skills |
| Testing | testing-vitest, testing-jest skills |
Anti-Patterns
| Anti-Pattern | Why It's Bad | Correct Approach |
|---|
Using var | Function scope, hoisting issues | Use const or let |
== instead of === | Type coercion bugs | Always use === |
| Mutating function parameters | Side effects, hard to debug | Return new object/array |
Missing await on Promise | Unhandled rejections | Always await or .catch() |
| Mixing ESM and CommonJS | Module system conflicts | Choose one, prefer ESM |
| Callback hell | Unreadable code | Use async/await |
| Not handling Promise rejections | Silent failures | Add .catch() or try/catch |
| Global variables | Namespace pollution | Use modules |
Quick Troubleshooting
| Issue | Cause | Solution |
|---|
| "X is not defined" | Variable not declared | Check spelling, imports |
| "Cannot read property of undefined" | Object is undefined | Use optional chaining ?. |
| "Promise rejected but not handled" | Missing .catch() | Add error handling |
| "Module not found" | Wrong import path | Check file path, extension |
| "Unexpected token" | Syntax error | Check for missing brackets, commas |
| "This is undefined" | Arrow function context | Use regular function or bind |
| Memory leak in event listeners | Not removing listeners | Use removeEventListener |
| Slow performance with large arrays | Inefficient algorithms | Use appropriate data structures |
When to Use JS vs TypeScript
| Scenario | Choice |
|---|
| New project | TypeScript |
| Quick scripts | JavaScript |
| Legacy codebase | JavaScript (gradual migration) |
| Public libraries | TypeScript with .d.ts |
| Prototype/MVP | JavaScript ok |
Reference Documentation
Deep Knowledge: Use mcp__documentation__fetch_docs with technology: javascript for comprehensive documentation.
Source: claude-dev-suite/claude-dev-suite — distributed by TomeVault.