NodeJS Coding Standards & Best Practices
NodeJS Coding Standards & Best Practices
1. Formatting
Use 4 spaces for indenting your code
Never mix tabs and spaces
Use UNIX-style newlines (\n).
A newline character as the last character of a file.
Windows-style newlines (\r\n) are forbidden inside any repository.
Clean up any trailing white space in your .js files before committing.
Limit your lines to 80 characters.
Use single quotes, unless you are writing JSON.
This helps you separate your objects’ strings from normal
strings. Like: var foo = ‘bar’;
Your opening braces go on the same line as the statement.
Like:
if (true) {
console.log(‘winning’);
}
2. Naming Conventions
Variables, properties and function names should use
LowerCamelCase. They should also be descriptive. Single character
variables and uncommon abbreviations should generally be avoided.
Class names should be capitalized using UpperCamelCase.
Constants should be declared as regular variables or static class
properties, using all uppercase letters.
3. Variables
While creating Arrays and Objects use trailing commas and put short
declarations on a single line.
Any non-trivial conditions should be assigned to a descriptively
named variable or function
4. Conditionals
Use the triple equality operator and it will work just as expected.
5. Functions
Write small functions.
To avoid deep nesting of if-statements, always return a function’s
value as early as possible
One method per line should be used if you want to chain methods.
6. Comments
Use slashes for both single line and multi line comments.
Try to write comments that explain higher level mechanisms or
clarify difficult segments of your code.
Don’t use comments to restate trivial things.
7. Miscellaneous
Always put requires at top of file to clearly illustrate a file’s
dependencies.
Always write your require statements in alphabetical order. This
makes it easier to find whether some package has been imported or
not.
Always do documentation of each method and class at the top of it
and define returning parameters and formal parameter.