Even though you should generally try to write your code in a way that doesn’t need comments, there are cases where they can be valid. Below are some examples.
Legal Comments
Sometimes your job will require you to put some legal comments at the beginning of your file. Maybe you’re using some open source code and you have to include the license. While these may not necessarily be good comments, they’re necessary.
Informative Comments
Sometimes it’s useful to include certain information in your code that will make it easier to understand. Regular expressions, and special formatting commands for printers are a good example.
// this regular expression matches for valid urls (http(s)?://)?([\w-]+\.)+[\w-]+[.com]+(/[/?%&=]*)?
Explanation of Intent
There can be times when your code can be clean, but it’s not clear why you chose to do something a certain way. Putting in comments that help understand or justify your reasoning can be of great help.
Clarification
Sometimes, you will have to return or use values that can be confusing, but there is little you can do to change them. Many older libraries or APIs receive and return numbers that are actually codes that represent something else. In cases like these a comment that clarifies the meaning of the number can help the code be easier to understand.
Warning of Consequences
There can be pieces of code that when executed may have consequences that can be correct but unexpected. In cases like this, a warning comment can be helpful.
TODO Comments
TODO comments are very helpful to leave yourself reminders of things that should be done, but are not the current task you’re carrying out. Maybe while you’re modifying a class you think of a more efficient way to implement a certain function. In those cases you can leave yourself a comment reminding you of the idea you had for after you finish your current task and can work on it.
Amplification
Amplification can be used to “highlight” the importance of a piece of code. At first glance it can be seen as trivial or even useless while it is actually very important to the task you’re performing. In those cases a comment can help prevent other people or your future self from thinking it’s “dead code” and deleting it.