Writing Code with Readability in Mind

Learn how to increase the readability of code using comments and documentation.

The importance of readable code

Code that we write will not just be executed by the computer. It will also be read both by ourselves and others. Therefore, it’s essential that we write code that’s as easy to read and understand as possible.

There are some simple rules we can follow that will assist in achieving readable code.

Using comments and documentation wisely

When creating code, you understand what you’re doing and why you’re doing it. But when you come back to the code a couple of months later, it isn’t always as clear what these thoughts were and why you wrote things the way you did. Commenting on tricky lines of code is a great way to document your thoughts for both your future self and others that will read your code.

But comments can also make the code less readable. Never comment on things that are obvious—these are things that any programmer, including yourself, will understand.

You should use comments when you look at a line of code and understand that a reader who sees this line will need to stop and think before understanding what it does.

Commenting on functions and methods is often a good idea. These comments will usually come right before the function or method or as the first thing inside it. What you should use depends on what language you’re using, as well as the conventions used by programmers of that language.

In the following code, we can see an example of this for a JavaScript function:

Get hands-on with 1400+ tech skills courses.