JavaScript Formatting: Write Clean Code
Clean JavaScript code is easier to read, debug, and maintain. Whether you’re writing a small script or a large application, consistent formatting is essential for professional development.
Why Format JavaScript?
1. Readability
Well-formatted code is easier to understand at a glance.
2. Team Collaboration
Consistent formatting helps teams work together effectively.
3. Debugging
Proper indentation makes errors more visible.
4. Code Reviews
Reviewers can focus on logic, not formatting disputes.
Basic Formatting Rules
Consistent Indentation
// Good - 2 spaces (common)
function greet(name) {
if (name) {
return `Hello, ${name}!`;
}
return 'Hello, World!';
}
// Good - 4 spaces (also common)
function greet(name) {
if (name) {
return `Hello, ${name}!`;
}
return 'Hello, World!';
}
Braces Style
// Most common
if (condition) {
doSomething();
}
// Also acceptable
if (condition)
{
doSomething();
}
Space Around Operators
// Good
const result = a + b * c;
if (x === 0) { }
// Avoid
const result=a+b*c;
if(x===0){ }
Using Our JS Formatter
Our JavaScript Formatter provides quick formatting:
- Paste your JavaScript code
- Click “Format” for readable output
- Click “Minify” for production-ready minified code
- Copy the result
Common Patterns
Function Declarations
// Named function
function calculateTotal(items) {
return items.reduce((sum, item) => sum + item.price, 0);
}
// Arrow function
const calculateTotal = (items) => {
return items.reduce((sum, item) => sum + item.price, 0);
};
// One-liner (for simple functions)
const double = (x) => x * 2;
Object Literals
const user = {
id: 1,
name: 'John Doe',
email: '[email protected]',
isActive: true,
roles: ['admin', 'user'],
profile: {
avatar: '/avatar.png',
bio: 'Software developer'
}
};
Arrays
// Multi-line for long arrays
const colors = [
'red',
'green',
'blue',
'yellow',
'purple'
];
// Single line for short arrays
const primaryColors = ['red', 'green', 'blue'];
Chained Methods
const result = users
.filter(user => user.isActive)
.map(user => user.name)
.sort()
.join(', ');
Code Conventions
Naming Conventions
// Variables - camelCase
const userName = 'John';
// Constants - UPPER_SNAKE_CASE or camelCase
const MAX_RETRIES = 3;
const apiBaseUrl = 'https://api.example.com';
// Functions - camelCase
function calculateTax(amount) {}
// Classes - PascalCase
class UserProfile {}
// Private properties - prefix with _
class User {
constructor() {
this._id = generateId();
}
}
Quotes
// Single quotes (common in JS)
const name = 'John';
// Double quotes (also acceptable)
const name = "John";
// Template literals for interpolation
const greeting = `Hello, ${name}!`;
Semicolons
// With semicolons (explicit)
const x = 1;
const y = 2;
// Without (relying on ASI)
const x = 1
const y = 2
// Recommended: use semicolons for clarity
Common Mistakes
1. Inconsistent Spacing
// Avoid
if(condition){
doSomething()
}
// Better
if (condition) {
doSomething();
}
2. Long Lines
// Hard to read
const result = someObject.method(arg1, arg2, arg3).anotherMethod(arg4, arg5).finalMethod();
// Better
const result = someObject
.method(arg1, arg2, arg3)
.anotherMethod(arg4, arg5)
.finalMethod();
3. Nested Callbacks
// Callback hell
getData(function(a) {
getMoreData(a, function(b) {
getMoreData(b, function(c) {
// ...
});
});
});
// Better - use async/await
const a = await getData();
const b = await getMoreData(a);
const c = await getMoreData(b);
Minification
When to Minify
Production JavaScript should be minified for:
- Smaller file sizes
- Faster downloads
- Better performance
Our Tool
// Input
function greet(name) {
return `Hello, ${name}!`;
}
// Output (minified)
function greet(n){return`Hello, ${n}!`}
Code Examples
Format JavaScript (Simple)
function formatJS(code) {
let indent = 0;
let result = '';
for (const char of code) {
if (char === '{') {
result += ' {\n' + ' '.repeat(++indent);
} else if (char === '}') {
result += '\n' + ' '.repeat(--indent) + '}\n';
} else if (char === ';') {
result += ';\n' + ' '.repeat(indent);
} else {
result += char;
}
}
return result;
}
Best Practices
1. Use a Linter
Tools like ESLint catch formatting issues automatically.
2. Use a Formatter
Prettier formats code automatically on save.
3. Follow a Style Guide
Popular guides:
- Airbnb JavaScript Style Guide
- Google JavaScript Style Guide
- StandardJS
4. Configure Your Editor
Enable format-on-save in VS Code or your preferred editor.
Conclusion
Clean JavaScript formatting is a hallmark of professional development. Use our JS Formatter for quick formatting and minification.
Remember: well-formatted code is a gift to your future self and your teammates!