Code indentation and formatting
The Importance of Code Indentation and Formatting
Good code indentation and formatting are key factors in improving code readability. Proper indentation clearly displays the hierarchical structure of the code, making logical relationships immediately apparent. In team collaboration, consistent formatting standards reduce comprehension costs and improve development efficiency.
Basic Indentation Rules
The JavaScript community generally adopts 2 spaces as the standard indentation unit. Compared to tabs, spaces display more consistently across different editors and environments.
// Correct 2-space indentation
function calculateTotal(items) {
let total = 0;
items.forEach(item => {
if (item.available) {
total += item.price * item.quantity;
}
});
return total;
}
Avoid mixing spaces and tabs, as this can cause display inconsistencies across environments. Modern editors can be configured to "convert tabs to spaces."
Block-Level Scope Formatting
There are two main styles for using curly braces {}
. The "same line" style is recommended:
// Recommended: Opening brace on the same line as the statement
if (condition) {
// ...
} else {
// ...
}
// Not recommended: Opening brace on a new line
if (condition)
{
// ...
}
For multi-level nested code, each level of nesting should add one level of indentation:
function processData(data) {
if (data) {
try {
data.items.forEach(item => {
if (item.valid) {
console.log(item.value);
}
});
} catch (error) {
console.error('Processing failed', error);
}
}
}
Chained Method Call Formatting
When method chains are too long, they should be broken into multiple lines with proper indentation:
// Good practice
const result = array
.filter(x => x > 10)
.map(x => x * 2)
.reduce((sum, x) => sum + x, 0);
// Bad practice
const result = array.filter(x => x > 10).map(x => x * 2).reduce((sum, x) => sum + x, 0);
Function Parameter Formatting
When a function has many parameters, they should be broken into multiple lines and aligned:
// Multiple parameters on new lines
function animate(
element,
duration,
easing = 'linear',
callback = () => {}
) {
// Implementation code
}
// Maintain the same style when calling
animate(
document.getElementById('box'),
300,
'ease-in-out',
() => console.log('Animation complete')
);
Array and Object Formatting
For multi-line arrays and objects, maintain consistent indentation:
// Array formatting
const colors = [
'red',
'green',
'blue',
'yellow'
];
// Object formatting
const config = {
apiUrl: 'https://api.example.com',
timeout: 5000,
retries: 3,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token'
}
};
Ternary Operator Formatting
Complex ternary expressions should be broken into multiple lines with proper indentation:
// Simple ones can stay on one line
const accessLevel = isAdmin ? 'admin' : 'user';
// Complex ones should be broken into lines
const message = isError
? 'An error occurred'
: isLoading
? 'Loading...'
: 'Data loaded successfully';
Template String Formatting
Multi-line template strings should maintain aligned indentation:
function createEmailTemplate(user) {
return `
Dear ${user.name},
Thank you for registering on our platform. Your account details:
Username: ${user.username}
Email: ${user.email}
Regards,
The Team
`.trim();
}
Conditional Statement Formatting
Complex conditionals should be broken into multiple lines:
if (
user.isAuthenticated &&
user.hasPermission('edit') &&
document.isEditable &&
!document.isLocked
) {
// Allow editing
}
Class and Method Definition Formatting
Class definitions and methods should follow consistent indentation rules:
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
getProfile() {
return {
name: this.name,
email: this.email,
lastLogin: this.lastLogin
};
}
updateEmail(newEmail) {
if (validateEmail(newEmail)) {
this.email = newEmail;
return true;
}
return false;
}
}
Module Import/Export Formatting
Imports should be grouped and formatted consistently:
// Third-party libraries
import React from 'react';
import PropTypes from 'prop-types';
// Utility functions
import { formatDate, parseCurrency } from './utils';
// Components
import Button from './Button';
import Input from './Input';
Comment Formatting
Comments should maintain the same indentation level as the code:
function complexCalculation(a, b, c) {
// First calculate the base value
const base = a * b;
/*
* Then apply the correction factor
* This factor accounts for various edge cases
*/
const adjusted = base + (c * 0.5);
return adjusted;
}
Automated Formatting Tools
Use tools to enforce consistent formatting automatically:
- ESLint - Define and enforce code style rules
- Prettier - Automatically format code
- EditorConfig - Maintain basic settings across editors
Example .eslintrc.js
configuration:
module.exports = {
indent: ['error', 2],
'linebreak-style': ['error', 'unix'],
quotes: ['error', 'single'],
semi: ['error', 'always'],
'comma-dangle': ['error', 'always-multiline']
};
Handling Special Cases
In some cases, temporary format adjustments may improve readability:
// Matrix data can remain compact
const transformationMatrix = [
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]
];
// Long lists of numbers can have multiple items per line
const PRIMES = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97
];
Formatting Standards in Team Collaboration
In team projects, you should:
- Add an
.editorconfig
file in the project root - Configure shared ESLint/Prettier rules
- Check formatting issues during code reviews
- Set up pre-commit hooks for automatic formatting
Example .editorconfig
file:
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
Formatting Legacy Code
When dealing with legacy code:
- Avoid making formatting-only changes in a single commit
- Gradually improve formatting while making functional changes
- Large-scale formatting should be a separate commit with clear notes
- Preserve
git blame
information
# Commit formatting changes separately
git commit -m "style: reformat code according to new guidelines"
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn