One of the rules of programming I mentioned in section 1 is commenting.
// or are included in a block delimited by
*/. The first is for one-line comments, the last is for multiline comments:
//this is a comment /* this is also a comment */
The first comments everything that’s on its right, on the current line.
The second can span over multiple lines and needs to be closed.
You can also use the second one on a single line:
/* this is also a comment */
What makes a good comment? It’s hard to say because it’s not an exact science, but we have some rules.
Make your comment explain the why, not the what
Your code should be well readable enough by your practice of choosing meaningful and self-explanatory variable names, function names and object names.
Comments should explain why you decided to write the code in that way. Maybe there is some constrain that was imposed beforehand and you have to workaround it and the code alone does not fully explain the matter.
Make sure the comments and the code agree
This might seem obvious. It’s easy when you start from a blank slate and you write the comments and the code together.
It’s also easy to forget to update a comment when you change something in the code. So keep this in mind, or you - or anyone working on the same codebase - will ask this question: “is the code correct and the comment is wrong, or is it wrong the code and the comment is right?”
Make every comment count. Don’t over-comment, but comment when necessary
When you see a file with more comments than code, it’s either generating the documentation automatically from the code - so there’s a reason for all those comments (example from Lodash).
But if not, you have to ask yourself some questions. Who is likely to read 20 lines of comment when reading the file?
On the other hand, if there’s 100 lines of code and 2 lines of comment before all the code blob, you are much more likely to pay it attention.
Scarcity is key here.
Of course make every comment count. You want it to be meaningful, to hold some valuable information.