JavaScript Style Guide
14 April 2025 | Category: JavaScript
A style guide in JavaScript is a set of rules and best practices that help developers write consistent code across a project or team. Following a consistent style improves readability, collaboration, and debugging efficiency.
đ 1. Use Consistent Naming Conventions
- CamelCase for variables and functions:
let userName = "John"; function getUserData() { }
- PascalCase for constructor functions or classes:
class UserProfile { }
- UPPER_CASE for constants:
const API_KEY = "123456";
đ 2. Use const
and let
Instead of var
var
is function-scoped and can cause bugs due to hoisting.const
is for variables that donât change.let
is for variables that might change.
const name = "Alice";
let age = 25;
đ 3. Use Strict Equality (===
) Instead of Loose Equality (==
)
Avoid unexpected type coercion.
// Bad
if (value == 0) { }
// Good
if (value === 0) { }
đ 4. Use Arrow Functions Where Appropriate
Shorter syntax and cleaner context handling.
// Traditional
function greet() {
return "Hello";
}
// Arrow
const greet = () => "Hello";
đ 5. Use Template Literals Instead of String Concatenation
// Bad
let greeting = "Hello, " + name + "!";
// Good
let greeting = `Hello, ${name}!`;
đ 6. Proper Indentation and Spacing
Consistent indentation improves readability.
// Good
if (isLoggedIn) {
showDashboard();
} else {
redirectToLogin();
}
- Use 2 or 4 spaces (pick one and stick with it).
- Always put spaces after commas, colons, and around operators.
đ 7. Keep Lines Short (Usually < 80-100 Characters)
Helps prevent horizontal scrolling and improves readability.
đ 8. Avoid Unnecessary Comments
Let code speak for itself. Use comments only when the logic is complex.
// â
Clear comment
// Calculate user discount based on age and membership status
đ 9. Use Semicolons
Although JavaScript can auto-insert semicolons, it’s safer to use them explicitly.
let total = 100;
console.log(total);
đ 10. Organize Code Logically
- Group related functions together.
- Use modules for separating code.
- Separate business logic from UI code.
đ 11. Prefer Descriptive Variable Names
// Bad
let x = true;
// Good
let isUserLoggedIn = true;
đ 12. Handle Errors Gracefully
Use try...catch
and proper error messages.
try {
const data = JSON.parse(json);
} catch (error) {
console.error("Invalid JSON format:", error.message);
}
đ 13. Use Linters and Formatters
- ESLint for enforcing style rules.
- Prettier for auto-formatting.
They help maintain consistency and catch issues early.
đ Example of Clean Code
const users = ["Alice", "Bob", "Charlie"];
function greetUser(userName) {
return `Hello, ${userName}!`;
}
users.forEach(user => {
console.log(greetUser(user));
});
đ Popular JavaScript Style Guides
â Final Thoughts
Following a style guide:
- Makes your code easier to read
- Reduces bugs
- Helps when working in teams
- Makes maintenance much easier