5. Comments and Readability
Code is read far more often than it is written. Comments help explain why the code is doing what it's doing.
1. Single-Line Comments
Use two forward slashes (//).
javascript // This line declares a variable to hold the user's name let userName = 'Alice';
let age = 30; // Inline comments can explain tricky parts
2. Multi-Line Comments
Used for longer explanations, or temporarily commenting out large blocks of code. Start with /* and end with */.
javascript /* This function calculates the total price, including tax and shipping costs. It needs three parameters: base price, tax rate, and a boolean flag for premium shipping. */ function calculateTotal(price, tax, premium) { // ... function logic }
Best Practices for Readability
- Meaningful Names: Variables and functions should clearly state their purpose (e.g., use
firstNameinstead offn). - Consistent Formatting: Use indentation (usually 2 or 4 spaces) consistently.
- Avoid Excessive Comments: If the code is clear, the comment is redundant.