General Principles
Code Readability
Write code that is easy to read and understand. Use descriptive names, consistent formatting, and clear logic. Favor explicitness over cleverness.
Example:
// Good: Clear and explicit
function calculateTotal(items) {
return items.reduce((sum, item) => sum + item.price, 0);
}
// Bad: Unclear and cryptic
function calc(x) {
let t = 0;
for (let i of x) t += i.p;
return t;
}
Consistency
Follow established conventions for naming, structure, and formatting. Consistent code is easier to maintain, review, and extend.
Example:
// Good: Consistent naming and formatting
let userName = 'John';
function getUserName() { return userName; }
// Bad: Inconsistent naming and formatting
let username = 'John';
function getusername(){return username;}
Simplicity
Keep code as simple as possible. Avoid unnecessary complexity, deep nesting, and over-engineering. Refactor complex logic into smaller, reusable functions or modules.
Example:
// Good: Simple, modular logic
function isAdult(age) {
return age >= 18;
}
// Bad: Overly complex
function check(a) {
if (a > 17) return true; else return false;
}
DRY (Don't Repeat Yourself)
Avoid duplicating code. Use reusable functions, modules, and templates to keep the codebase maintainable.
Example:
// Good: Reusable function
function formatDate(date) {
// ...
}
let d1 = formatDate(date1);
let d2 = formatDate(date2);
// Bad: Duplicate logic
let d1 = date1.toISOString().slice(0, 10);
let d2 = date2.toISOString().slice(0, 10);
Separation of Concerns
Organize code so that each module or function has a single responsibility. Keep business logic out of views and templates; use modules and services for data and logic.
Example:
// Good: Separate data logic from UI
function fetchUserData() {
// ...fetch logic...
}
function renderUser(user) {
// ...UI logic...
}
// Bad: Mixed logic
function showUser() {
// fetch and render in one function
}
Rationale
Following these principles leads to maintainable, scalable, and bug-resistant code. It also improves team collaboration and onboarding.
Advanced Tips
- Refactor complex logic into smaller, testable modules.
- Use comments and documentation for non-obvious decisions.
- Review code for adherence to these principles during code reviews.