Writing Clean JavaScript

Writing clean JavaScript means creating code that is easy to read, maintain, and debug. Clean code reduces errors and improves collaboration.

Illustration of Writing Clean JavaScript
Illustration of Writing Clean JavaScript

💡 Consistency is Key

Use consistent naming, spacing, and syntax throughout your code to improve readability.

1. Use Meaningful Variable and Function Names

Choose descriptive names that clearly explain the purpose of variables and functions.

Good vs Poor Naming
Poor NamingGood Naming
let x = 10;let userAge = 10;
function d(){}function calculateDiscount(){}

2. Keep Functions Small and Focused

Each function should perform a single task. This makes debugging and testing easier.

⚠️ Avoid Long Functions

Functions longer than 20-30 lines are harder to understand and maintain.

3. Use Consistent Formatting and Indentation

Indent code blocks properly and follow a consistent style for braces, spaces, and line breaks.

Formatting Example
InconsistentConsistent
if(x>5){console.log("Hi");}if (x > 5) { console.log("Hi"); }

4. Avoid Global Variables

Global variables can lead to conflicts and bugs. Use local variables or encapsulate code inside functions or modules.

5. Use Comments Sparingly and Effectively

Comments should explain why something is done, not what the code does. Well-written code often needs fewer comments.

6. Prefer Const and Let Over Var

Use const for variables that don’t change and let for those that do. Avoid var to prevent scope-related bugs.

📌 Deep Dive: Using Const and Let

JAVASCRIPT
const maxUsers = 100;
let currentUsers = 0;

function addUser() {
  if (currentUsers < maxUsers) {
    currentUsers++;
  }
}

7. Use Early Returns to Reduce Nesting

Return early from functions when possible to avoid deep nesting and improve readability.

📌 Deep Dive: Early Return

JAVASCRIPT
function isAdult(age) {
  if (age < 18) return false;
  return true;
}

8. Avoid Magic Numbers and Strings

Replace unexplained literals with named constants.

📌 Deep Dive: Magic Numbers

JAVASCRIPT
const MAX_ATTEMPTS = 5;

for (let i = 0; i < MAX_ATTEMPTS; i++) {
  // attempt login
}

💡 Use Linters and Formatters

Tools like ESLint and Prettier can automatically enforce code style and highlight potential issues.