How to improve your code?

How to improve your code?

Tips for how to write clean and simple code

ยท

4 min read

Hi ๐Ÿ‘‹, probably youโ€™ve been in a situation where your code becomes unreadable even for you. In that case, I will show you a couple of tips so your code will become more readable.

1. Namings

Writing meaningful and understandable names is of great help to you and the people that will read the code.

Variables

First, when trying to come up with a good name for a variable you should ask yourself: "What will store this variable?", "What will be its type?", "For what I will use it?".
Let's see an example:

const hasUserSubscription = useQuery(USER_QUERY).status;

Here we want to know whether the user has a subscription or not.
The variable stores the user's subscription status and the type is boolean so the proper name should be (has)UserSubscription.

Avoid shortening names as it makes code unreadable and chaotic. For example:

const acc = document.querySelector(); // Accordion or Accumolator?
const accordion = document.querySelector();

options.forEach((o) => {});
options.forEach((option) => {});

words.filter(w => w.length > 6);
words.filter(word => word.length > 6);

Sometimes more text = better understating

Functions

The function's name should mirror the action that will take place.
Before naming it, you should ask yourself the following:
"What will this function do?", "Will the function return something?", "Will the function be reused?".
Let's see an example:

/**
 * Change username
 *
 * @param {string} username
 * @param {string} newUsername
 */
function changeUsername(username, newUsername) {
    username.innerText = newUsername;
}

As we see the function will change a username and can be reused.

Now, a function that returns some value is good to specify what you will get from it. For example (get)AllUsers returns all user's names, so it's best to use get as its action name:

/**
 * Get all user names
 *
 * @returns {Array[{name: string}]} usernames
 */
function getAllUsernames() {
    return useQuery(USERS_QUERY).usernames;
}

Naming pattern for Functions/Methods

Often I need to come up with a simple name for a function or method and I usually follow this pattern:

init + noun โœ… - initNavigation, initFooter, initProfileInfo

handle + verb or noun โœ… - handleUserChanges, handleCarouselView

init + handle ๐Ÿšซ - initHandleNavigation

verb + noun โœ… - updateAccordion, deleteUserData

Good variable and function names should be easy to understand and tell you what is going on โ€” not more and not less.

2. JS Documentation

For your code to be readable not only from you but from others also, it's best to add documentation to your files and functions. Short descriptions should be clear, simple, and brief.

Functions: What does the function do? What parameters does it expect?

  • Good: Handles a click on X element.

  • Bad: Included for back-compat for X element.

/**
 * Handles a click on X 
 *
 * @param {type} name - Description.
 */

For more info on how to use JSDoc, see https://jsdoc.app/

3. Comments

Sometimes your business logic requires a little bit of complex code. In those situations, it's best for you and the others to have comments where needed in order to not struggle to read it after a month.

For example:


    function sortAlphabetically() {
        let mixedCaseAnimals = ['Cat', 'Elephant', 'bee', 'ant'];

        mixedCaseAnimals.sort(function (a, b) {
            let x = a.toUpperCase(),
                y = b.toUpperCase();
            // 0 keep original order
            // 1 sort a after b, e.g. [b, a]
            // -1 sort a before b, e.g. [a, b]
            return x == y ? 0 : x > y ? 1 : -1;
        });
    }

sortAlphabetically() -> [ 'ant', 'bee', 'Cat', 'Elephant' ]

4. Follow Basic Style Guide

Most projects include linters to make sure your code follows the project's specific style guide. Even though there's a linter that will fail your code to be executed or pushed, it's good to know and follow a basic style guide.

  • Code indentation - Always use 2 spaces for indentation of code blocks

  • Statement rules - Always end a simple statement with a semicolon.

  • Line length - For readability, avoid lines longer than 100 characters.

  • Spacings (give your code space to breathe)

    • Use one space before the opening bracket

    • Add space between properties - const number = 123; / const number=123;

Summary

These are some of the basic rules. A clean readable code doesn't come that easy, you will make mistakes and learn from them. Just don't rush, take your time to organize your thoughts and when you're done go through the code you wrote and check if there's something which can be done in a better way.

Thanks for reading this article, hope it was helpful! If you have some tips for improving code readability you can share them in the comments section. ๐Ÿ˜Š

Resources

https://www.w3.org/wiki/JavaScript_best_practices

https://developer.wordpress.org/coding-standards/inline-documentation-standards/javascript/#what-should-be-documented

https://www.w3schools.com/js/js_conventions.asp

ย