Adhering to a consistent coding style is essential for maintaining readability, reducing bugs, and facilitating collaboration in software development. Below are key coding standards for JavaScript, complete with examples.
1. Indentation
Use 2 Spaces for Indentation
Always indent your code with 2 spaces. Mixing tabs and spaces is a cardinal sin that can lead to a special kind of hell in your codebase.
Example:
function greet() {
console.log('Hello, World!');
}
2. Newlines
Use UNIX-style Newlines
Always use \n
for newlines, and ensure that every file ends with a newline character.
Example:
console.log('This is a line.'); // Ends with \n
3. No Trailing Whitespace
Eliminate Trailing Whitespace
Just as you wouldn’t leave crumbs on a table, don’t leave trailing whitespace in your files. Clean up before committing.
Example:
var name = 'John'; // No trailing space here
4. Use Semicolons
Always Use Semicolons
It’s a community value to end statements with semicolons, which helps avoid potential pitfalls of automatic semicolon insertion.
Example:
var foo = 'bar';
console.log(foo);
5. Line Length
Limit Lines to 80 Characters
While screens have expanded, our cognitive load hasn’t. Keep your lines to 80 characters for better readability.
Example:
var veryLongVariableNameThatCouldBeShortened = 'This is an example of a long line that should be broken up.';
6. String Quotes
Use Single Quotes
For strings, prefer single quotes unless working with JSON.
Example:
var message = 'Hello, World!';
7. Brace Placement
Opening Braces on the Same Line
Place opening braces on the same line as the statement.
Example:
if (true) {
console.log('winning');
}
8. Variable Declarations
Declare One Variable per var
Statement
This practice makes it easier to reorder variables.
Example:
var keys = ['foo', 'bar'];
var values = [23, 42];
9. Naming Conventions
- Variables, Properties, and Function Names: Use lowerCamelCase.
- Class Names: Use UpperCamelCase.
- Constants: Use UPPERCASE.
Example:
var adminUser = 'admin';
function BankAccount() {}
const MAX_USERS = 100;
10. Object and Array Creation
Use Trailing Commas
When creating objects and arrays, use trailing commas and keep short declarations on one line.
Example:
var array = ['hello', 'world'];
var obj = {
key1: 'value1',
key2: 'value2',
};
11. Conditionals
Use the ===
Operator
Always use strict equality checks.
Example:
var a = 0;
if (a !== '') {
console.log('winning');
}
Descriptive Conditions
Assign complex conditions to descriptively named variables.
Example:
var isValidPassword = password.length >= 4 && /^(?=.*\d).{4,}$/.test(password);
if (isValidPassword) {
console.log('winning');
}
12. Functions
Write Small Functions
Keep functions concise, ideally fitting within ~15 lines.
Example:
function isPercentage(val) {
return val >= 0 && val <= 100;
}
Return Early
Minimize nesting by returning early from functions.
Example:
function isPositive(val) {
if (val <= 0) {
return false;
}
return true;
}
13. Naming Closures
Name Your Closures
Providing names to closures enhances readability and debugging.
Example:
req.on('end', function onEnd() {
console.log('winning');
});
14. Comments
Use Slashes for Comments
Write comments that explain the 'why' behind your code, not the 'what.'
Example:
// This function processes user input and handles errors gracefully.
function processInput(input) {
// ...
}
15. Miscellaneous
Keep require
Statements at the Top
Organize dependencies clearly at the beginning of your files.
Example:
var express = require('express');
var app = express();
Avoid Extending Built-in Prototypes
This practice can lead to unexpected behavior.
Example:
var a = [];
if (!a.length) {
console.log('Array is empty.');
}
Conclusion
Following these coding standards will make your JavaScript code cleaner, more maintainable, and collaborative-friendly. Stick to these guidelines, and you’ll be well on your way to writing excellent code.