5 Tips to Write Clean Code in JavaScript

5 Tips to Write Clean Code in JavaScript

Write cleaner JavaScript with these 5 principles

As you become more experienced with JavaScript there are tips and principles on how to write clean code that you should know.

The craft of software engineering is a relatively new one. The craft of medicine has existed for thousands of years while software engineering has only been around since the beginning of the 1960s. We are all still learning how to write clean code. There are some principles though that are widely accepted by the community as best practices.

There are many principles for writing clean code, but I decided to focus on the five most important. These tips are recommendations and not strict rules. Practice these principles and your code will be cleaner!

Why Clean Code Is Important

As a beginner, your focus is not necessarily on writing clean code. Your focus should be on getting the code working and your tests passing. As you become more experienced you can start focusing on writing clean code.

In this article, I define clean code as:

  • Easy to read
  • Easy to understand

Clean code will help you get up-to-speed with and maintain a codebase. It's always worth the effort of making your code cleaner, even if it takes a longer time to write!

Write Clean Code in JavaScript

JavaScript, like any other language, has its special quirks. These tips are not necessarily limited to JavaScript and can be used for many other languages.

Extract Magic Numbers to Constants

"Magic numbers" refer to numbers that are used directly in the code, without any context. They lack meaning and should be extracted to constants with a meaningful variable name.

Bad:

const isOldEnough = (person) => {
  // What does 100 refer to? This is a so-called "magic number"
  return person.getAge() >= 100;
}

Good:

const AGE_REQUIREMENT = 100; // Now we know what 100 refers to

const isOldEnough = (person) => {
  return person.getAge() >= AGE_REQUIREMENT;
}

Avoid Boolean Function Arguments

Boolean function arguments are a typical "code smell" (breaking fundamental programming standards). This is because they lack meaning. And it indicates that your function does more than one thing, which you should always avoid!

Bad:

const validateCreature = (creature, isHuman) => {
  if (isHuman) {
    // ...
  } else {
    // ...
  }
}

Good:

const validatePerson = (person) => {
  // ...
}

const validateCreature = (creature) => {
  // ...
}

Encapsulate Conditionals

Long conditional statements are hard to read because you have to keep all of them in your head. By encapsulating them into a function or a variable your code will be easier to reason about.

Bad:

if (
  person.getAge() > 30 &&
  person.getName() === "simon" &&
  person.getOrigin() === "sweden"
) {
  // ...
}

Good:

const isSimon =
  person.getAge() > 30 &&
  person.getName() === "simon" &&
  person.getOrigin() === "sweden";

if (isSimon) {
  // ...
}

// OR use a function

const isSimon = (person) => {
  return (
    person.getAge() > 30 &&
    person.getName() === "simon" &&
    person.getOrigin() === "sweden"
  );
};

if (isSimon(person)) {
  // ...
}

Avoid Negative Conditionals

Negative conditionals ("double negation") add an extra condition to your brain when you're reading the code. You would not say "I'm not not sleepy". You would say "I'm sleepy". The same practice applies to code!

Bad:

const isCreatureNotHuman = (creature) => {
  // ...
}

if (!isCreatureNotHuman(creature)) {
  // ...
}

Good:

const isCreatureHuman = (creature) => {
  // ...
}

if (isCreatureHuman(creature)) {
  // ...
}

Don't Use If Statements

This might sound crazy, but hear me out! If statements are easy to understand but do not scale. As soon as you have more than one or two if statements in the same function the code easily becomes hard to reason about.

Instead, use a switch statement or, if possible, a data structure like Array, Set, or Map.

Bad:

const isMammal = (creature) => {
  if (creature === "human") {
    return true;
  } else if (creature === "dog") {
    return true;
  } else if (creature === "cat") {
    return true;
  }
  // ...

  return false;
}

Good:

const isMammal = (creature) => {
  switch (creature) {
    case "human":
    case "dog":
    case "cat":
    // ...
      return true;
    default:
      return false;
  }
}

// OR even better, use a data structure

const isMammal = (creature) => {
  const mammals = ["human", "dog", "cat", /* ... */];
  return mammals.includes(creature);
}

Conclusion

These are my five most important principles for writing clean code in JavaScript. Practice makes perfect, and the same goes for writing code. If you already follow these principles today - keep it up! I'm sure you've practiced writing code a lot. If not - don't be discouraged! We all start somewhere 🙂

To summarise:

  • Extract Magic Numbers to Constants
  • Avoid Boolean Function Arguments
  • Encapsulate Conditionals
  • Avoid Negative Conditionals
  • Don't Use If Statements

Connect with me on Twitter, LinkedIn, or GitHub

Did you find this article valuable?

Support Simon Egersand 🎈 by becoming a sponsor. Any amount is appreciated!