The best kind of code is a code that is easily readable by humans and can be executed by machines without any errors. When coding you don't want to sacrifice functionality over readability or vice versa. You should code in a way that other developers can read it without chugging two cups of coffee before going through your code. So, here are some tips to make your code cleaner -(These are not ancient rules that are written in gold or on pieces of rocks, that you must follow. But if you follow them you can achieve an easy-to-read code.)
- Use a single space between parameters.
//Don't
function add(numb1,numb2,numb3,numb4){...}
//Do
function add(numb1, numb2, numb3, numb4){...}
- Use a single space between arguments.
//Don't
let result = add(3,2,1)
//Do
let result = add(3, 2, 1)
- Don't use space between function name and opening parenthesis.
//Don't
function add (numb1,numb2){...}
//Do
function add(numb1, numb2){...}
- For better readability you can indent your code. Use 2 Spaces or 1 Tab. 4 Spaces or 2 Tabs are overkill.
//Don't
function add(numb1,numb2){
return numb1 + numb2;
}
//Do
function add(numb1, numb2){
return numb1 + numb2;
}
- Use the opening curly brace on the same line as your function.
//Don't
function add(numb1,numb2)
{ return numb1 + numb2 }
//Do
function add(numb1, numb2){
return numb1 + numb2;
}
- Use a single space around your operators ( + - * / ).
//Don't
function add(numb1,numb2,numb3){
return numb1+numb2+numb3;
}
//Do
function add(numb1, numb2, numb3){
return numb1 + numb2 + numb3;
}
- An empty line is a good choice to increase readability, but make sure you don't overdo it. You can use an empty line between two logical blocks.
//Don't
function add(numb1,numb2){
return numb1 + numb2;
}
let result = potato(2, 3);
//Do
function add(numb1, numb2){
return numb1 + numb2;
}
let result = add(2, 3);
- Use a single space after for/while/if.
- If you have more than 2 conditions in your if statement breaks them down into individual lines.
//Don't
if (id === 001 && color === "black" && category === "shoe")
//DO
if (
id === 001 &&
color === "black" &&
category === "shoe"
)
- Avoiding 'else' is a good practice (Why you may ask?? That is a topic for another post.) But if you want to use 'else', use it without a line break.
//Don't
if(...){
...........
}
else {.......}
//Do
if(...){
........
} else {
......
}
Bonus
If you want to learn more you can read Google JavaScript Style Guide
Or if you are a work-shy developer like me you can use an extension called prettier- code format. It will format your code in a standard manner.
Top comments (0)