Commenting code

Dec 18, 2022·

2 min read

Play this article

There's a lot of stuff out there that tells you that too many comments are bad and too few comments are bad. So how do you find that sweet spot?

Comment for your future self

Imagine you're coming back to this code in six months. You just need to make one quick change, but you look at it and think "why did I do that?". You then spend some time experimenting and discover the reason. Or don't and replace that one weird bit of code. Wouldn't it have saved some time if you'd written a comment? For example:

// Usually this would be XYZ but that doesn't work because of [something in another function]


/* Not using XYZ here because it conflicts with [something else] */

Comment to make things easier to find

If you're writing CSS and it's all in one big file, it can be hard to find things. You can search, but what if you're looking for something hard to search for like an a tag? You can use comments to separate the code out a bit so when you're scrolling through you can easily see where a new section is. For example:

/********************** Header **********************/
header {
  /* Some code here */

/********************** Footer **********************/
footer {
  /* Some code here */

Obviously you'd have a lot more code between those commented section headers, but you can easily see the difference in colour.

Noting where you got something from

You've implemented some clever thing that you got from StackOverflow. It can be useful to note the link, so you can go back to it in the future. Maybe because it's not working as well as it did before and you need another explanation to understand what the code is doing. Or maybe because something changed in the language and someone has offered a way to do the same thing that works with the change.