JavaScript Style Guide
Writing clean, readable, and consistent JavaScript code
✨ Why Follow a Style Guide?
A style guide helps you write consistent, readable code that other developers (including future you) can easily understand and maintain!
// ❌ Hard to read
function calc(x,y){return x*y+10}
// ✅ Easy to read
function calculateTotal(price, tax) {
return price * tax + 10;
}
Style Guide Areas
Naming
Clear, descriptive names
Formatting
Consistent spacing and layout
Comments
Explaining complex logic
Structure
Organizing code logically
🔹 Naming Conventions
Use clear, descriptive names that explain what your code does:
🔸 Variables and Functions
// ❌ Bad naming
let x = 25;
let d = new Date();
function calc(a, b) { return a * b; }
// ✅ Good naming
let userAge = 25;
let currentDate = new Date();
function calculateArea(width, height) {
return width * height;
}
🔸 Constants
// ❌ Bad
const pi = 3.14159;
const max = 100;
// ✅ Good
const PI = 3.14159;
const MAX_USERS = 100;
const API_BASE_URL = 'https://api.example.com';
🔸 Classes and Constructors
// ✅ Use PascalCase for classes
class UserAccount {
constructor(username, email) {
this.username = username;
this.email = email;
}
sendWelcomeEmail() {
// Implementation here
}
}
🔹 Code Formatting
Consistent formatting makes code easier to read:
🔸 Indentation and Spacing
// ✅ Good formatting
function processUserData(users) {
const results = [];
for (let i = 0; i < users.length; i++) {
const user = users[i];
if (user.isActive) {
results.push({
id: user.id,
name: user.name,
email: user.email
});
}
}
return results;
}
🔸 Object and Array Formatting
// ✅ Multi-line for readability
const userConfig = {
name: 'Alice Johnson',
email: '[email protected]',
preferences: {
theme: 'dark',
notifications: true,
language: 'en'
}
};
const colors = [
'red',
'green',
'blue',
'yellow'
];
🔹 Function Guidelines
Write functions that are clear, focused, and reusable:
🔸 Function Length and Purpose
// ❌ Function doing too much
function processUser(user) {
// Validate user
if (!user.email || !user.name) return false;
// Format name
user.name = user.name.trim().toLowerCase();
// Send email
sendEmail(user.email, 'Welcome!');
// Save to database
database.save(user);
// Log activity
console.log(`User ${user.name} processed`);
}
// ✅ Separate concerns
function validateUser(user) {
return user.email && user.name;
}
function formatUserName(name) {
return name.trim().toLowerCase();
}
function processUser(user) {
if (!validateUser(user)) {
return false;
}
user.name = formatUserName(user.name);
sendWelcomeEmail(user);
saveUser(user);
logUserActivity(user);
return true;
}
🔸 Function Parameters
// ✅ Clear parameter names and defaults
function createUser(name, email, options = {}) {
const defaults = {
isActive: true,
role: 'user',
notifications: true
};
return {
name,
email,
...defaults,
...options
};
}
// Usage is clear
const newUser = createUser('Alice', '[email protected]', {
role: 'admin',
notifications: false
});
🔹 Comments and Documentation
Write helpful comments that explain the "why", not just the "what":
🔸 Good Comments
// ✅ Explains the reasoning
function calculateDiscount(price, userType) {
// Premium users get 15% discount, regular users get 5%
// This helps increase customer retention
const discountRate = userType === 'premium' ? 0.15 : 0.05;
return price * (1 - discountRate);
}
// ✅ Documents complex logic
function findOptimalRoute(locations) {
// Using greedy algorithm for traveling salesman problem
// Not optimal but good enough for small datasets (< 20 locations)
let currentLocation = locations[0];
const route = [currentLocation];
// ... implementation
}
🔸 JSDoc Comments
/**
* Calculates the total price including tax
* @param {number} price - The base price
* @param {number} taxRate - Tax rate as decimal (0.08 for 8%)
* @param {Object} options - Additional options
* @param {boolean} options.includeShipping - Whether to include shipping
* @returns {number} The total price including tax
*/
function calculateTotal(price, taxRate, options = {}) {
let total = price * (1 + taxRate);
if (options.includeShipping) {
total += 10; // Standard shipping fee
}
return total;
}
🔹 Error Handling Style
Handle errors consistently and gracefully:
// ✅ Consistent error handling
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error(`Failed to fetch user: ${response.status}`);
}
const userData = await response.json();
return userData;
} catch (error) {
console.error('Error fetching user data:', error.message);
// Return a safe default or re-throw based on context
return null;
}
}
// ✅ Input validation
function divide(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new Error('Both arguments must be numbers');
}
if (b === 0) {
throw new Error('Cannot divide by zero');
}
return a / b;
}
🔹 Modern JavaScript Style
Use modern JavaScript features for cleaner code:
🔸 Use const and let
// ❌ Old style
var userName = 'Alice';
var userAge = 25;
// ✅ Modern style
const userName = 'Alice'; // Won't change
let userAge = 25; // Might change
🔸 Arrow Functions
// ✅ Use arrow functions for short operations
const users = ['Alice', 'Bob', 'Charlie'];
// Short and clear
const upperCaseNames = users.map(name => name.toUpperCase());
// For longer functions, regular functions are fine
function processComplexData(data) {
// Multiple lines of logic here
return result;
}
🔸 Template Literals
// ❌ String concatenation
const message = 'Hello ' + userName + ', you have ' + messageCount + ' messages.';
// ✅ Template literals
const message = `Hello ${userName}, you have ${messageCount} messages.`;
🔹 Popular Style Guides
Consider following established style guides:
Popular JavaScript Style Guides:
- Airbnb JavaScript Style Guide - Very popular and comprehensive
- Google JavaScript Style Guide - Used by Google
- Standard JS - No configuration needed
- Prettier - Automatic code formatting
Tools to Help:
- ESLint - Finds and fixes problems in your code
- Prettier - Automatically formats your code
- VS Code Extensions - Real-time style checking