How to Write Clean Code: an Overview of JavaScript Best Practices and Coding … Coding conventions are style guidelines for programming.

Introduction

Coding conventions are style guidelines for programming. They typically cover:

  • Naming and declaration rules for variables and functions.
  • Rules for the use of white space, indentation, and comments.
  • Programming practices and principles

In this article, I’m going to cover most important JavaScript code conventions. If you stick to the rules stated in this article, people will perceive your work differently. Your team and your boss will appreciate you for writing clean code, but most importantly, you will be thankful to yourself. Everyone appreciates clean code.

Coding conventions **secure quality, improve code readability and make code maintenance easier. **They can be documented rules for teams to follow, or just be your individual coding practice.

“Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.” - Robert C. Martin
Let’s get started!

Just a note

Along with writing this article, I have also created a YouTube Video.

In the video, I go into much greater detail of each specific coding convention and I throw in a few extra examples to verify each specific rule.

Here’s a link to the full video: https://www.youtube.com/watch?v=RMN_bkZ1KM0.

Coding Conventions

To start, let’s begin by asking what isn’t clean code? Our examples will be based around JavaScript.

So what are some of the things you can start doing to make it easier for you and your team? Let’s start with simple naming conventions.

Always use the same coding conventions for all your JavaScript projects.

Magic numbers

Assigning a number that has no clear meaning. If you look at this code for a first time, you will have no idea what the number 86400 should represent.

for(let i = 0; i < 86400; i += 1) {
  // ...
}

It’s better to replace it with a named constant:

const SECOND_IN_A_DAY = 86400;

for(let i = 0; i < SECOND_IN_A_DAY; i += 1) {
  // ...
}

Later in article you’ll also learn why we used upper case snake case for this example.

Deep nesting

If your code contains many nested loops or conditional statements, then this should probably be extracted into a separate function.

const exampleArray = [ [ [ 'value' ] ] ];

exampleArray.forEach((arr1) => {
  arr1.forEach((arr2) => {
    arr2.forEach((el) => {
      console.log(el)
    })
  })
})

// output: 'value'

For this particular example, we can create a function that will loop through all arrays and return a final value:

const exampleArray = [ [ [ 'value' ] ] ];

const retrieveFinalValue = (element) => {
  if(Array.isArray(element)) {
    return fetchValue(element[0]);
  }

  return element;
}

// output: 'value'

Stop writing comments

Although subjective, the use of comments in your code can be helpful, but could be a sign your code is failing to be self explanatory.

“While comments are neither inherently good or bad, they are frequently used as a crutch. You should always write your code as if comments didn’t exist. This forces you to write your code in the simplest, plainest, most self-documenting way you can humanly come up with.” - Jeff Atwood
Code must speak for itself!

Avoid large functions

A function or even a class that is large in size suggests that it’s doing more than it should. This example may seem simple, but it proves a point. This function does a lot more than it should be doing.

const addMultiplySubtract = (a, b, c) => {
  const addition = a + b + c;
  const multiplication = a * b * c;
  const subtraction = a - b - c;

  return `${addition} ${multiplication} ${subtraction}`;
}

It is better to create different functions to separate the logic:

const add = (a, b, c) => a + b + c;
const multiply = (a, b, c) => a * b * c;
const subtract = (a, b, c) => a - b - c;

Code repetition

If you have to copy and paste a block of code, it’s a sign that that the repeated block may need to be extracted into its own function.

Great example of this is our deep nesting example:

const exampleArray = [ [ [ 'value' ] ] ];

exampleArray.forEach((arr1) => {
  arr1.forEach((arr2) => {
    arr2.forEach((el) => {
      console.log(el)
    })
  })
})

In here, we have a lot of repeated code. It’s much better to extract it to a separate it into a different function and handle logic differently, with less repetition:

const exampleArray = [ [ [ 'value' ] ] ];

const retrieveFinalValue = (element) => {
  if(Array.isArray(element)) {
    return fetchValue(element[0]);
  }

  return element;
}

Another great example of code repetition would be retrieving data from parameters:

const getUserCredentials = (user) => {
  const name = user.name;
  const surname = user.surname;
  const password = user.password;
}

Using ES6 object destructuring we can simply do the following:

const getUserCredentials = (user) => {
  const { name, surname, password } = user;
}

Variable Names

Camel case is used for almost everything in JavaScript. Camel case is a naming standard we use for identifier names (variables and functions).

It states that a name needs to begin with a lower-case letter and then, every first letter of the next word is uppercased. Here are some examples:

thisIsARandomCamelCaseName, camelCase, exampleFunctionName, you get the point.

Use meaningful names

getUserData and getUserInfo are vague. What data or info are you getting?

It is important that our functions, methods and variable names express their exact meaning.

getUserPost is much better, we can understand exactly what we’re getting.

When in doubt, favor descriptive over concise

Be as concise as possible; however, if you are having difficulty finding a two or three word description for your name, it is better to stay on the side of being descriptive.

findUserByNameOrEmail and setUserLoggedInTrue is better than findUser.

When there is a shorter version, use it

While getUserFromDatabase is very descriptive, there is a shorter version that means the same thing. The keq question you should ask yourself is “does fromDatabase add any meaning t0 your program?”

The answer is that it most likely doesn’t, we can assume that we’re fetching the user from the database.

Use consistent verbs per concept

Functions will usually create, read, update or delete something. You could even be a bit more descriptive and say they: create, get, set, add, remove, reset, and delete things.

A function should be a verb or a verb phrase, and must communicate its intent.

We need to be consistent with our verbs, for fetching we can always use get, rather than get, retrieve, return and ten thousand different names:

getQuestions getUserPosts getUsers rather than:

getQuestions returnUsers retrieveUsers.

Obviously, there are different variations of these words, but whichever you choose, stay consistent. For example, when you remove something use “delete” or “remove” (not both) throughout your entire program.

Make booleans that read well in if-then statements

A good test for boolean variable names is to put the name in an if-then statement and read it outloud. If it reads like a natural sentence, you’re in a good shape.

For example, if we’re checking the characteristics of a car, which naming would you find more convenient?

sedan, sold, green, airbag, or;

isSedan, isSold, isGreen, hasAirbag.

And now if we’re checking the properties, we can do something like this:

car.isSedan, car.isSold, car.hasAirbag (much better than car.airbags) and we immediately know that we’re dealing with boolean values.

Those sound more natural and make the program easier to decipher.

Use nouns for classNames

Classes don’t take things, they are things.

More specifically, they are a blueprint for something. Instantiating a class is what makes something.

class Car = {...} and not class MakeCar {...}.

If you were to make a new car you wouldn’t say “make a new MakeCar”, you would say: “make a new Car”.

Use PascalCase for classNames.

Pascal case makes it easier to see which items are classes and which items aren’t.

class Task {...} rather than class task {...}.

Capitalize constant values

Remember that we specified the seconds in a day like SECOND_IN_A_DAY = 86400?

A constant value is something that won’t change. This convention has roots in C and is not always followed in JavaScript.

Keep in mind const and the term constant are not the same. The const declaration simply means the value can’t me mutated through reassignment. Whereas a true constant value is a primitive value that won’t be changed later.

Also, you may consider narrowing the definition to values that are not only primitive but also inherently fixed: such as hours in a day, the value of PI, or the names of days in a week.

For example:

const HOURS_IN_DAY = 24; and const USER_AGE = 30; are primitive values that aren’t going to change, variables that are not set in stone should not be capitalized: const USER = foundUser; const TODAY = new Date ();.

Avoid one-letter variable names

A shortened names causes more hassle than the keystrokes you save in the long run.

Names should be concise and descriptive. A variable initialized in the global scope may end up being use one hundred lines later. It becomes easy to forget what it was if it is only a single letter.

const dueDate = new Date() is much better than const d = new Date();

const query = () => { ... }; is much better than const q = () => { ... };

If you use a single-letter variable names, limit them to small function or as index variables in loops (this is okay):

for(let i = 0; i < 10>; i ++) { // ... }

Remember these conventions for your own future sanity.

Summary

To summarise, there are huge benefits to following these rules in the long run. Others may pick up the code you’ve written in a few days, months or even years, scan from top to bottom, and either sigh of relief or frustration. Which one would you prefer?

Clean code makes it easier to start and continue coding it is better for the individual as well as a team and it is much easier to read.

Characteristics of a Clean code:

  1. “It should be elegant — Clean code should be *pleasing *to read. Reading it should make you smile the way a well-crafted music box or well-designed car would.”
  2. “Clean code is focused —Each function, each class, each module exposes a single-minded attitude that remains entirely undistracted, and unpolluted, by the surrounding details.”
  3. “Clean code is taken care of. Someone has taken the time to keep it simple and orderly. They have paid appropriate attention to details. They have cared.”

#javascript #web-development

How to Write Clean Code: an Overview of JavaScript Best Practices and Coding Conventions
4 Likes68.25 GEEK