Writing Clean, Maintainable Code
Following best practices makes your code easier to read, maintain, and debug, both for you and other developers.
Good code style, consistent naming conventions, proper error handling, and modern JavaScript features all contribute to code quality.
These practices become increasingly important as projects grow in size and complexity, or when working in teams.
Example
// ❌ Bad Practice: var, unclear names, no const
var x = 10;
var y = 20;
var z = x + y;
// ✅ Good Practice: const/let, descriptive names
const price = 10;
const quantity = 20;
const totalCost = price * quantity;
// ❌ Bad: Long function, does too much
function processUser(u) {
const n = u.n.toUpperCase();
const e = u.e.toLowerCase();
const a = new Date().getFullYear() - u.b;
return { n, e, a };
}
// ✅ Good: Small focused functions, clear names
function formatUserData(user) {
return {
name: formatName(user.name),
email: formatEmail(user.email),
age: calculateAge(user.birthYear)
};
}
function formatName(name) {
return name.toUpperCase();
}
function formatEmail(email) {
return email.toLowerCase();
}
function calculateAge(birthYear) {
return new Date().getFullYear() - birthYear;
}
// ✅ Use template literals instead of concatenation
const name = 'Alice';
const age = 30;
const message = `Hello, my name is ${name} and I am ${age} years old.`;
// ✅ Use arrow functions for callbacks
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
// ✅ Use destructuring
const user = { name: 'Bob', age: 25, email: 'bob@example.com' };
const { name: userName, email } = user;
// ✅ Always use === instead of ==
if (value === 5) { } // Good
if (value == 5) { } // Bad (type coercion)
// ✅ Avoid global variables
// Bad: Global pollution
let globalCount = 0;
// Good: Use modules or IIFE
const counter = (function() {
let count = 0;
return {
increment: () => ++count,
get: () => count
};
})(); - Use const/let - Never use var (const by default, let when reassignment needed)
- Descriptive Names - Use clear, meaningful variable and function names
- Small Functions - Each function should do one thing well
- Template Literals - Use backticks for string interpolation
- Arrow Functions - Use for callbacks and short functions
- Strict Equality === - Avoid == (loose equality)
- Comments - Explain why, not what (code should be self-documenting)
- Error Handling - Always handle errors, don't ignore them
- DRY Principle - Don't Repeat Yourself, reuse code
- Consistent Style - Follow a style guide (Airbnb, Standard, Google)
Compare Code Quality
HTML
<div class="practices-demo">
<h3>Best Practices Examples</h3>
<div class="example">
<h4>Example 1: String Formatting</h4>
<div class="code-comparison">
<div class="bad-code">
<h5>❌ Bad Practice:</h5>
<pre>var msg = "Hello, " + name +
"! You are " + age + " years old.";</pre>
</div>
<div class="good-code">
<h5>✅ Good Practice:</h5>
<pre>const message = `Hello, ${name}!
You are ${age} years old.`;</pre>
</div>
</div>
<button id="stringDemo">Run String Demo</button>
<div id="stringOutput"></div>
</div>
<div class="example">
<h4>Example 2: Function Design</h4>
<button id="badFunctionBtn">Run Bad Code</button>
<button id="goodFunctionBtn">Run Good Code</button>
<div id="functionOutput"></div>
</div>
<div class="example">
<h4>Example 3: Data Processing</h4>
<button id="dataDemo">Process User Data</button>
<div id="dataOutput"></div>
</div>
</div> CSS
.practices-demo {
padding: 20px;
max-width: 800px;
}
.example {
margin: 20px 0;
padding: 15px;
background: #f5f5f5;
border-radius: 8px;
}
h4, h5 {
margin-top: 0;
color: #333;
}
.code-comparison {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 15px;
margin: 15px 0;
}
.bad-code, .good-code {
padding: 10px;
border-radius: 4px;
}
.bad-code {
background: #ffebee;
border-left: 4px solid #f44336;
}
.good-code {
background: #e8f5e9;
border-left: 4px solid #4CAF50;
}
pre {
margin: 10px 0 0 0;
font-family: 'Courier New', monospace;
font-size: 12px;
white-space: pre-wrap;
word-wrap: break-word;
}
button {
padding: 10px 15px;
margin: 5px;
background: #2196F3;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
}
button:hover {
background: #1976D2;
}
#goodFunctionBtn {
background: #4CAF50;
}
#goodFunctionBtn:hover {
background: #45a049;
}
#stringOutput, #functionOutput, #dataOutput {
margin-top: 10px;
padding: 12px;
background: white;
border: 2px solid #ddd;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 13px;
min-height: 40px;
}
.success {
border-color: #4CAF50 !important;
background-color: #e8f5e9 !important;
} JavaScript
// Example 1: String Formatting
document.getElementById('stringDemo').addEventListener('click', function() {
const name = 'Alice';
const age = 30;
const city = 'New York';
// Bad: String concatenation
console.log('=== Bad Practice (Concatenation) ===');
var badMessage = "Hello, " + name + "! You are " + age + " years old and live in " + city + ".";
console.log(badMessage);
// Good: Template literals
console.log('=== Good Practice (Template Literals) ===');
const goodMessage = `Hello, ${name}! You are ${age} years old and live in ${city}.`;
console.log(goodMessage);
const output = document.getElementById('stringOutput');
output.className = 'success';
output.innerHTML = '<strong>Check console for comparison!</strong><br><br>' +
'Template literals are:<br>' +
'• More readable<br>' +
'• Easier to maintain<br>' +
'• Support multi-line strings<br>' +
'• Allow embedded expressions';
});
// Example 2: Function Design
// Bad: One big function doing multiple things
function badProcessUserData(u) {
var n = u.name;
var e = u.email;
var a = u.age;
n = n.toUpperCase();
e = e.toLowerCase();
if (a < 18) {
return "Too young";
}
return n + " (" + e + ") - " + a;
}
// Good: Small, focused functions
const formatName = (name) => name.toUpperCase();
const formatEmail = (email) => email.toLowerCase();
const isAdult = (age) => age >= 18;
function goodProcessUserData(user) {
if (!isAdult(user.age)) {
return 'User must be 18 or older';
}
return {
name: formatName(user.name),
email: formatEmail(user.email),
age: user.age,
status: 'verified'
};
}
document.getElementById('badFunctionBtn').addEventListener('click', function() {
const user = { name: 'john doe', email: 'JOHN@EXAMPLE.COM', age: 25 };
const result = badProcessUserData(user);
const output = document.getElementById('functionOutput');
output.innerHTML = '<strong>Bad Code Result:</strong><br>' +
result + '<br><br>' +
'<strong>Issues:</strong><br>' +
'• Unclear variable names (u, n, e, a)<br>' +
'• Does too many things<br>' +
'• Uses var instead of const/let<br>' +
'• Hard to test individual pieces';
});
document.getElementById('goodFunctionBtn').addEventListener('click', function() {
const user = { name: 'john doe', email: 'JOHN@EXAMPLE.COM', age: 25 };
const result = goodProcessUserData(user);
const output = document.getElementById('functionOutput');
output.className = 'success';
output.innerHTML = '<strong>Good Code Result:</strong><br>' +
JSON.stringify(result, null, 2) + '<br><br>' +
'<strong>Benefits:</strong><br>' +
'• Clear, descriptive names<br>' +
'• Small, focused functions<br>' +
'• Easy to test and maintain<br>' +
'• Uses const and arrow functions';
});
// Example 3: Modern JavaScript Features
document.getElementById('dataDemo').addEventListener('click', function() {
const users = [
{ name: 'Alice', age: 30, active: true },
{ name: 'Bob', age: 17, active: true },
{ name: 'Charlie', age: 25, active: false },
{ name: 'Diana', age: 35, active: true }
];
// Using modern array methods and destructuring
const activeAdults = users
.filter(({ age, active }) => age >= 18 && active)
.map(({ name, age }) => ({ name: name.toUpperCase(), age }));
const output = document.getElementById('dataOutput');
output.className = 'success';
output.innerHTML = '<strong>Active Adult Users:</strong><br>' +
JSON.stringify(activeAdults, null, 2) + '<br><br>' +
'<strong>Modern features used:</strong><br>' +
'• Array filter() and map()<br>' +
'• Destructuring in parameters<br>' +
'• Arrow functions<br>' +
'• Method chaining';
}); Notes
- Consistency Matters: Pick a style guide and stick to it. Use tools like ESLint to enforce rules automatically.
- Code Reviews: Have others review your code - fresh eyes catch issues and improve code quality.
- Refactor Regularly: Don't be afraid to improve old code. Refactoring is a normal part of development.
