Loading...
Loading...
This skill should be used when the user asks to "write JavaScript code", "follow JavaScript style guide", "format JS files", "create Node.js scripts", or needs guidance on JavaScript/Node.js coding standards and best practices.
npx skill4agent add the-perfect-developer/the-perfect-opencode javascript_-.jsmy_module.jsuser-service.js\'\"\\\b\f\n\r\t\v∞\u221eimportexport// Imports
import './sideeffects.js';
import * as goog from '../closure/goog/goog.js';
import {name, value} from './sibling.js';
// Named exports only (no default exports)
export class Foo { ... }
export function bar() { ... }
// Or export together
class Foo { ... }
function bar() { ... }
export {Foo, bar};.jslowerCamelCaseimport * as fileOne from '../file-one.js';// Use const by default
const MAX_COUNT = 100;
const users = [];
// Use let only when reassignment needed
let currentIndex = 0;
// NEVER use var// Good
const a = 1;
const b = 2;
// Bad
const a = 1, b = 2;// Good - declared when needed
function process(items) {
// ... some code ...
const result = items.map(x => x * 2);
return result;
}class InnerClass {
constructor() {}
method(foo) {
if (condition(foo)) {
try {
something();
} catch (err) {
recover();
}
}
}
}elsecatchwhile// Good
if (condition) {
doSomething();
}
// Exception: single-line if without else
if (shortCondition()) foo();
// Bad
if (condition)
doSomething();importexport from// Good
currentEstimate =
calc(currentEstimate + x * currentEstimate) /
2.0;
// Bad
currentEstimate = calc(currentEstimate + x *
currentEstimate) / 2.0;if (for (catch (functionsuperfunction(super(if (x) {class Foo {a + bx ? y : zfoo(a, b);{a: 1, b: 2}//// commentconst x = 1; // Required
doSomething(); // Required// Use trailing commas
const values = [
'first value',
'second value',
];
// Never use Array constructor
const a = [x1, x2, x3]; // Good
const b = new Array(x1, x2, x3); // Bad
// Destructuring
const [a, b, c, ...rest] = generateResults();
let [, b,, d] = someArray; // Skip unused elements
// Spread operator
[...foo] // Preferred over Array.prototype.slice.call(foo)
[...foo, ...bar] // Preferred over foo.concat(bar)// Use trailing commas
const obj = {
a: 0,
b: 1,
};
// Never use Object constructor
const o = {a: 0, b: 1}; // Good
const o = new Object(); // Bad
// Don't mix quoted and unquoted keys
{
width: 42,
height: 50,
} // Good - all unquoted (struct style)
{
'width': 42,
'maxWidth': 43,
} // Good - all quoted (dict style)
{
width: 42,
'maxWidth': 43,
} // Bad - mixed
// Method shorthand
const obj = {
value: 1,
method() {
return this.value;
},
};
// Shorthand properties
const foo = 1;
const bar = 2;
const obj = {foo, bar};
// Destructuring
function process({num, str = 'default'} = {}) {}class MyClass {
// Constructor
constructor(value) {
/** @private @const */
this.value_ = value;
/** @private */
this.mutableField = 0;
}
// Methods
getValue() {
return this.value_;
}
/** @override */
toString() {
return `MyClass(${this.value_})`;
}
}
// Inheritance
class ChildClass extends MyClass {
constructor(value, extra) {
super(value); // Must call super() first
this.extra = extra;
}
}@const@private@protectedsuper()this// Good
const squares = numbers.map(n => n * n);
items.forEach((item) => {
process(item);
});
// Use when 'this' from outer scope needed
class Timer {
start() {
setInterval(() => {
this.tick(); // 'this' refers to Timer instance
}, 1000);
}
}thisx => x * 2() => 42(a, b) => a + bfunction myFunction(param1, param2) {
return param1 + param2;
}
// Optional parameters with defaults
function greet(name = 'Guest') {
return `Hello, ${name}`;
}
// Rest parameters
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}// Standard if-else
if (condition) {
doSomething();
} else if (otherCondition) {
doOther();
} else {
doDefault();
}
// Ternary for simple cases
const value = condition ? trueValue : falseValue;// For-of for iterables
for (const item of items) {
process(item);
}
// Traditional for loop
for (let i = 0; i < array.length; i++) {
process(array[i]);
}
// For-in for object properties (use with caution)
for (const key in object) {
if (object.hasOwnProperty(key)) {
process(object[key]);
}
}switch (value) {
case 'option1':
handleOption1();
break;
case 'option2':
handleOption2();
break;
default:
handleDefault();
}// Use for string interpolation
const message = `Hello, ${name}!`;
// Multi-line strings
const html = `
<div>
<h1>${title}</h1>
</div>
`;// Prefer async/await
async function fetchData() {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.error('Failed:', error);
throw error;
}
}
// Promise chains when appropriate
fetch(url)
.then(response => response.json())
.then(data => process(data))
.catch(error => console.error(error));// Single-line comments use //
// Multiple single-line comments for
// longer explanations.
/*
* Multi-line comment style.
* Subsequent lines start with * aligned
* with the * on the previous line.
*/
// Parameter name comments for clarity
someFunction(obviousParam, /* shouldRender= */ true, /* name= */ 'hello');/**
* Brief description of the function.
*
* @param {string} name The user's name
* @param {number=} age Optional age parameter
* @return {string} Greeting message
*/
function greet(name, age) {
return `Hello, ${name}`;
}
/**
* Class representing a point.
*/
class Point {
/**
* Create a point.
* @param {number} x The x coordinate
* @param {number} y The y coordinate
*/
constructor(x, y) {
/** @private @const {number} */
this.x_ = x;
/** @private @const {number} */
this.y_ = y;
}
}// ES modules in Node.js (use .mjs or "type": "module" in package.json)
export class Service {}
export function helper() {}
// CommonJS (when ES modules not available)
class Service {}
function helper() {}
module.exports = {Service, helper};// Always handle errors in async code
async function processFile(path) {
try {
const content = await fs.promises.readFile(path, 'utf8');
return JSON.parse(content);
} catch (error) {
console.error(`Failed to process ${path}:`, error);
throw error;
}
}
// Use Error objects
throw new Error('Something went wrong');
throw new TypeError('Expected string');// Check existence
if (obj.property != null) {
// Property exists and is not null/undefined
}
// Use optional chaining
const value = obj?.deeply?.nested?.property;
// Nullish coalescing
const result = value ?? defaultValue;// Prefer array methods over loops
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);
// Check if array contains item
if (array.includes(item)) { }
// Find item
const found = array.find(item => item.id === targetId);constletvar'`lowerCamelCaseUpperCamelCase.js///* */references/advanced-features.mdreferences/jsdoc-guide.mdreferences/naming-conventions.mdreferences/disallowed-features.md