DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for 5 Tips to Write Clean Code in JavaScript
Simon Egersand 🎈
Simon Egersand 🎈

Posted on

5 Tips to Write Clean Code in JavaScript

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; 
}
Enter fullscreen mode Exit fullscreen mode

Good:

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

const isOldEnough = (person) => {
  return person.getAge() >= AGE_REQUIREMENT;
}
Enter fullscreen mode Exit fullscreen mode

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 {
    // ...
  }
}
Enter fullscreen mode Exit fullscreen mode

Good:

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

const validateCreature = (creature) => {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

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"
) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

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)) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

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)) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

Good:

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

if (isCreatureHuman(creature)) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
laianbraum profile image
Laian Braum

Hey Simon, nice article! Dev.to recommended it to me and I really enjoyed the read. Very well written and good points raised.

To foment the discussion, I'd like to point out something

  1. Nested if statements and switch cases
  • The good part
    • Switch cases are way more readable than if's statements when we're talking about multiple conditionals.
  • The solution
    • Object literals! They are as readable as switch statements. You can be as creative as you want with them, so you're not forced to break any pattern or standard.

Instead of

switch (dayOfTheWeek)) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
    day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
    break;
  default: 
    throw new Error("Hey! We have only 7 days in the week");
}
Enter fullscreen mode Exit fullscreen mode

How about

const dayOfTheWeek = {
  0: "Sunday",
  1: "Monday",
  2: "Tuesday",
  3: "Wednesday",
  4: "Thursday",
  5: "Friday",
  6: "Saturday",
};

console.log('day of the week:', dayOfTheWeek[new Date().getDay()]);
Enter fullscreen mode Exit fullscreen mode
Collapse
simeg profile image
Simon Egersand 🎈 Author

Hi! Thanks!

I totally agree with you. I used a list as an example but objects are definitely better than switch cases when there are many cases!

Thanks for sharing 😌

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.