How to Write Readable Code In JavaScript

Every so often, there's an article with some list of rules on how to keep your code readable. Everyone wants their code to be self-documenting, but nobody seems to agree on how to do it.

If you're reading this article, chances are you know your code isn't the cleanest. If your code works, does it matter if it's a bit messy?

It does. It really does.

Readable code reduces cognitive load. It makes working with it easier and faster.

Learning to write self-documenting code isn't about being a better developer, it's about being a better teammate.

To help you on your journey to writing readable code, I've established some guidelines. These are by no means the be-all-end-all of code readability. Instead, they form a base for you to start with and expand on.

Use a style guide

The simplest and most immediate thing you can do to improve your code readability is to use a style guide.

Code with inconsistent styling is like trying to read a kidnapper's note, pieced together from magazine cuttings.

You can read it, but it's definitely more difficult.

If you're not already using a style guide, I'd recommend picking up a public one like the AirBnB Style Guide. These are written to improve readability, so you should notice an immediate improvement in your code.

The specific rules of the style guide aren't all that crucial, though. It's more important that you're consistent. Feel free to chop and change your style guide to suit you and your team.

Use clear names

What can you tell about the following functions?

  • List.a()
  • List.add()
  • List.addItem()

One thing is for sure -- the longer the name gets, the clearer it gets.

I'm not sure why, but when I was starting out, I had a thing about not writing long function and variable names. I'd abbreviate, or use vague descriptors all for the sake of brevity.

I'm going to save you some pain right now. A long variable name is better than an unclear variable name.

When you come back in two weeks, you won't remember what that a function or variable does.

Use a lot of small named functions

Function names are one of the hidden gems of code readability. Aside from preventing code repetition, functions are a powerful tool for telling a story. Look at this.

const handleClick = function updateTitleOnClick(event) {
	event.preventDefault();
    const titleKey = event.target.getAttribute('data-new-title');
    titleService.getTitle(titleKey).then((title) => {
    	document.querySelector('#title').innerText = title;
    });
}

It's definitely possible to tell what's going on, but what if we break things into small functions, and give our anonymous functions names?

const handleClick = function updateTitleOnClick(event) {
	event.preventDefault();
    getButtonTitle(event.target)
    	.then(updateTitle);
}

const getButtonTitle = function getButtonTitle(button) {
	const key = button.getAttribute('data-new-title');
	return titleService.getTitle(key)
}

const updateTitle = function updateTitle(title) {
	document.querySelector('#title').innerText = title;
}

This is much cleaner. It's immediately obvious what steps the handleClick function is taking. All we had to do was add two more functions.

Don't use Magic Numbers

Magic numbers are a real readability problem. Tell me what the following code means:

if (items.length > 15) {
	// What even is this?
}

This is because it's hard to tell what it's doing, and why it's there. What does this 15 represent? Is this 15 the same as the 15 further down in the code?

Instead, prefer to use named variables over directly using primitives in code.

const MAX_CART_SIZE = 15;
if (items.length > MAX_CART_SIZE) {
	// It's pretty clear what this is now
}

Use comments sparingly

Comments are a contentious point in self-documenting code. Purists believe that if you think you need comments, you actually need to rewrite your code to be clearer.

This staunch opposition to comments is because bad comments can reduce code readability while providing no value:

// Set the numerator and denominator
const numerator = 5;
const denominator = 4;

// Calculate the division and round it
const result = 5 / 4;
result = Math.round(result);

That being said, no amount of clean code can replace a well-placed comment or real documentation.

Comments are difficult enough to warrant an article of their own. The gist is that you want your comments to capture information that you can't tell from the code alone.

function example() {
	// We had to use doFunc() here instead of setFunc() because setFunc()
    // isn't compatible with someOtherFunc()
    return doFunc();
}

It can be hard to tell when these kinds of comments are warranted. When in doubt, just leave the comment. Better to leave redundant information than to miss out something important.

Remember it's all subjective

One of the reasons code readability is so hard to get right is that it's different for everyone. 10-year industry veterans don't read code the same as people three weeks in.

Nobody is going to work with your own code as much as you, so write code to your standard.

Now that you've finished the article, go back to one of your old projects and clean it up. You'll be surprised what a difference it makes.

Can't get past JavaScript Tutorials?

Download my FREE ebook on how to succeed as a self-taught JavaScript Developer, and how to find projects that you'll actually finish. Learn More...

Read more