Berat Aras

Software Engineer

Blog

Writing Clean Code with JavaScript ES6

6 min read

Clean code doesn't just mean code that works. In fact, writing code that works is easy. For example, all of us could open a single JS file and write all the code we'll ever write in that same file, without even splitting it into separate files. We could create functions and name them however we like, with one uppercase letter and one lowercase letter alternating. We could never use methods and do our filtering with nested loops. Compilers and engines generally don't care about things like this, but society does 🙂 Nobody who wants to be, or already is, a good developer wants to be remembered as "the previous developer who messed everything up." Ethically, is it enough as professional ethics for the code to be well written once it works? That's a separate topic of debate. Let's look at what clean code actually is;

Clean code, in the general sense, means code that can be easily read and updated by other developers. To produce such code, we don't just need code that works; we need code that broadly follows community conventions, where the names of declared variables, classes and functions are easy to understand, that is split up in a meaningful way, and that is built by using nearly all the capabilities of the language in use.

I will try to convey the right clean code practices for JavaScript, but these practices can generally be used in other languages as well.

1. Variables

Use meaningful names

The basic rule in JavaScript is that almost all naming is done in Camel Case (camelCase). Also, in no programming language, JS included, should variables, functions, etc. be named in anything other than English. (Imagine opening the editor and seeing a variable in Japanese? Even the thought makes me shiver…)

// Yanlış ❌
const eposta = "berat@example.com";
const firstname = "Berat";
const IsActive = 21;
const aktifMi = true;
// Doğru ✅
const email = "berat@example.com";
const firstName = "Berat";
const age = 21;
const isActive = true;

We also name booleans. For these, too, English question-style prefixes are used:

isActive;
didOnline;
hasSharePost;

Don't add unnecessary context to names

I run into this most often in column naming in MySQL. The table's name is already "user", so why write "user_name, user_surname" again underneath it? Let's drop this silliness! 🤨

Likewise here, if our object is user, there's no need to put the user prefix again on the properties beneath it.

// Yanlış ❌
const user = {
  userId: "1",
  userEmail: "tayfun@example.com",
  userFirstName: "Tayfun",
  userLastName: "Erbilen",
};
user.userId;
// Doğru ✅
const user = {
  id: "1",
  email: "berat@example.com",
  firstName: "Berat",
  lastName: "Aras",
};
user.id;

Don't use Hardcode

Instead of adding fixed values, it's better to create meaningful and updatable values.

// Yanlış ❌
setTimeout(clearSessionData, 900000);
// Doğru ✅
const duration = 15 * 60 * 1000;
setTimeout(clearSessionData, duration);

2. Functions

Use descriptive names, long if necessary

Function names can be long; there's no problem with that. Generally, the action performed inside the function is what gets described. For example, the Turkish logic goes like this: "putTheTeaOnTheStove", "getInTheCarStartTheEngine"

Also, Camel Case is used in function names too. (Kebab case has a place in our hearts.)

// Yanlış ❌
function toggle() {
  // ...
}
function agreed(user) {
  // ...
}
// Doğru ✅
function toggleThemeSwitcher() {
  // ...
}
function didAgreeToAllTerms(user) {
  // ...
}

Use default values for parameters

Instead of adding an extra check inside the function, assign a default value to the parameter you define in the parentheses.

// Yanlış ❌
function getFilesInDirectory(dir) {
  const directory = dir || "./";
  //   ...
}
// Doğru ✅
function getFilesInDirectory(dir = "./") {
  // ...
}

Limit the number of parameters

A function should take at most 3 arguments. Sometimes even three can be considered too many, but if there are more than three, there can be 2 reasons for it:

  • The function is doing more than one job and needs to be split up.
  • The data passed to the function is related and can be passed by putting it into an object or array.
// Yanlış ❌
function sendPushNotification(title, message, image, isSilent, delayMs) {
  // ...
}
sendPushNotification("New Message", "...", "http://...", false, 1000);
// Doğru ✅
function sendPushNotification(notification, user) {
  const title = notification.title;
}
const notificationConfig = {
  title: "New Message",
  message: "...",
  image: "http://...",
  isSilent: false,
  delayMs: 1000,
};
sendPushNotification(notificationConfig, userName);

A function should do only one thing

When we create a class or build a functional structure, a function should have only a single task. As an example, let's take a function to be a waiter in a restaurant. Normally, the waiter bringing your orders can bring more than one thing. For example, they might have your drink in one hand and your food in the other. But this shouldn't happen in a function; in a function, the waiter should only bring your food. While one function brings your food, another function should bring your drink. That way we understand better exactly what each function does.

// Yanlış ❌
function pingUsers(users) {
  users.forEach((user) => {
    const userRecord = database.lookup(user);
    if (!userRecord.isActive()) {
      ping(user);
    }
  });
}
// Doğru ✅
function pingInactiveUsers(users) {
  users.filter(!isUserActive).forEach(ping);
}
function isUserActive(user) {
  const userRecord = database.lookup(user);
  return userRecord.isActive();
}

Don't use flag arguments

If you've had to use a flag argument, it means this function could be split further and simplified.

As you can see here, instead of creating a single createFile function and checking whether it's public with isPublic, we created two separate functions named createFile and createPublicFile. That way each function has only one task and a cleaner structure emerged.

// Yanlış ❌
function createFile(name, isPublic) {
  if (isPublic) {
    fs.create(`./public/${name}`);
  } else {
    fs.create(name);
  }
}
// Doğru ✅
function createFile(name) {
  fs.create(name);
}
function createPublicFile(name) {
  createFile(`./public/${name}`);
}

Don't repeat yourself

Perhaps the mistake we make most as developers is repeating our code. If code is repeated somewhere, something is going wrong and it means we haven't built our structure correctly.

// Yanlış ❌
function renderCarsList(cars) {
  cars.forEach((car) => {
    const price = car.getPrice();
    const make = car.getMake();
    const brand = car.getBrand();
    const nbOfDoors = car.getNbOfDoors();
    render({ price, make, brand, nbOfDoors });
  });
}
function renderMotorcyclesList(motorcycles) {
  motorcycles.forEach((motorcycle) => {
    const price = motorcycle.getPrice();
    const make = motorcycle.getMake();
    const brand = motorcycle.getBrand();
    const seatHeight = motorcycle.getSeatHeight();
    render({ price, make, brand, seatHeight });
  });
}
// Doğru ✅
function renderVehiclesList(vehicles) {
  vehicles.forEach((vehicle) => {
    const price = vehicle.getPrice();
    const make = vehicle.getMake();
    const brand = vehicle.getBrand();
    const data = { price, make, brand };
    switch (vehicle.type) {
      case "car":
        data.nbOfDoors = vehicle.getNbOfDoors();
        break;
      case "motorcycle":
        data.seatHeight = vehicle.getSeatHeight();
        break;
    }
    render(data);
  });
}

Did we notice the unnecessary repetition here? The developer who wrote the code copied a whole function and created a new one just because of a single differing variable 🙃 Yet switch-case is the most basic structure we see in software. Using it, we were able to handle the check of that single variable. Of course, an if-else structure can also be used here if desired.

Don't mutate a global constant's structure

In English they call this "Avoid side effects". In short, it's this; for example, you have a variable named date that holds a certain date, and you want to split the date in this variable into day, month and year. You split it, but instead of assigning the split result back to the date variable, create a variable named newDate and let the original stay as it is.

// Yanlış ❌
let date = "23-01-2000";
function splitIntoDayMonthYear() {
  date = date.split("-");
}
splitIntoDayMonthYear();
console.log(date); // ['23', '01', '2000'];
// Doğru ✅
function splitIntoDayMonthYear(date) {
  return date.split("-");
}
const date = "21-8-2021";
const newDate = splitIntoDayMonthYear(date);
console.log(date); //date aynı şekilde kaldı.
console.log(newDate); //newDate ise böldüğümüz tarih şeklinde.

The same applies when we want to add an element to an Array. Instead of adding it into the same Array, copy a new Array and add it there. We can do this easily with the spread operator that came with ECMAScript.

// Yanlış ❌
function enrollStudentInCourse(course, student) {
  course.push({ student, enrollmentDate: Date.now() });
}
// Doğru ✅
function enrollStudentInCourse(course, student) {
  return [...course, { student, enrollmentDate: Date.now() }];
}
//Gördüğünüz gibi burada course Array'ide kopyalanıp yeni bir Array oluşturuluyor.

3. Conditionals

Use non-negative conditional expressions

// Yanlış ❌
function isUserNotVerified(user) {
  // ...
}
if (!isUserNotVerified(user)) {
  // ...
}
// Doğru ✅
function isUserVerified(user) {
  // ...
}
if (isUserVerified(user)) {
  // ...
}

Use shorthands whenever possible

Here the great importance of using the capabilities of the language becomes even more apparent.

// Yanlış ❌
if (isActive === true) {
  // ...
}
if (firstName ! "" && firstName ! null && firstName !== undefined) {
  // ...
}
const isUserEligible = user.isVerified() && user.didSubscribe() ? true : false;
// Doğru ✅
if (isActive) {
  // ...
}
if (!!firstName) {
  // ...
}
const isUserEligible = user.isVerified() && user.didSubscribe();

Don't create unnecessary lines and brackets

// Yanlış ❌
function addUserService(db, user) {
  if (!db) {
    if (!db.isConnected()) {
      if (!user) {
        return db.insert("users", user);
      } else {
        throw new Error("No user");
      }
    } else {
      throw new Error("No database connection");
    }
  } else {
    throw new Error("No database");
  }
}
// Doğru ✅
function addUserService(db, user) {
  if (!db) throw new Error("No database");
  if (!db.isConnected()) throw new Error("No database connection");
  if (!user) throw new Error("No user");
  return db.insert("users", user);
}

In fact, a ternary might be even better:

function addUserService(db, user) {
  !db && throw new Error("No database");
  !db.isConnected() && throw new Error("No database connection");
  !user && throw new Error("No user");
  return db.insert("users", user);
}

Sometimes using an Object instead of Switch is better

In such a case, using objects and maps is better in terms of performance and code readability.

// Yanlış ❌
const getColorByStatus = (status) => {
  switch (status) {
    case "success":
      return "green";
    case "failure":
      return "red";
    case "warning":
      return "yellow";
    case "loading":
    default:
      return "blue";
  }
};
// Doğru ✅
const statusColors = {
  success: "green",
  failure: "red",
  warning: "yellow",
  loading: "blue",
};
const getColorByStatus = (status) => statusColors[status] || "blue";

4. Concurrency

Callbacks waste your life

Instead of callbacks, use Promises, which also came with ES6, or the Async/Await syntax.

// Yanlış ❌
getUser(function (err, user) {
  getProfile(user, function (err, profile) {
    getAccount(profile, function (err, account) {
      getReports(account, function (err, reports) {
        sendStatistics(reports, function (err) {
          console.error(err);
        });
      });
    });
  });
});
// Doğru ✅
// Promise
getUser()
  .then(getProfile)
  .then(getAccount)
  .then(getReports)
  .then(sendStatistics)
  .catch((err) => console.error(err));
// veya Async/Await ✅
async function sendUserStatistics() {
  try {
    const user = await getUser();
    const profile = await getProfile(user);
    const account = await getAccount(profile);
    const reports = await getReports(account);
    return sendStatistics(reports);
  } catch (e) {
    console.error(err);
  }
}

5. Error Handling

I don't think I need to say why this is an extremely important rule. Spending time now to handle errors properly will save your time later.

// Yanlış ❌
try {
  // olası hatalı kod
} catch (e) {
  console.log(e);
}
// Doğru ✅
try {
  // olası hatalı kod
} catch (e) {
  // 1- eğer varsa kullanıcıya
  alertUserOfError(e);
  // 2- server'a raport et
  reportErrorToServer(e);
  // 3- özel hata işleme
  throw new CustomError(e);
}

6. Comments

Only explain complex logic and algorithms

Writing clean code frees us from excessive comments. Comments can be used only in the parts that will be hard to follow. By the way, comments should also be in English if possible. 🙃

// Yanlış ❌
function generateHash(str) {
  // Hash variable
  let hash = 0;
  // Get the length of the string
  let length = str.length;
  // If the string is empty return
  if (!length) {
    return hash;
  }
  // Loop through every character in the string
  for (let i = 0; i < length; i++) {
    // Get character code.
    const char = str.charCodeAt(i);
    // Make the hash
    hash = (hash << 5) - hash + char;
    // Convert to 32-bit integer
    hash &= hash;
  }
}
// Doğru ✅
function generateHash(str) {
  let hash = 0;
  let length = str.length;
  if (!length) {
    return hash;
  }
  for (let i = 0; i < length; i++) {
    const char = str.charCodeAt(i);
    hash = (hash << 5) - hash + char;
    hash = hash & hash; // Convert to 32bit integer
  }
  return hash;
}

Don't do version control inside the code

Unnecessary comments also make code unreadable. Since version control systems already exist and we use them, don't do version control inside the code.

// Yanlış ❌
/**
 * 2021-7-21: Fixed corner case
 * 2021-7-15: Improved performance
 * 2021-7-10: Handled mutliple user types
 */
function generateCanonicalLink(user) {
  // const session = getUserSession(user)
  const session = user.getSession();
  // ...
}
// Doğru ✅
function generateCanonicalLink(user) {
  const session = user.getSession();
  // ...
}

If possible, write short documentation for the code

For example, here a comment has been written about what the arguments coming into a function are. You'll often come across comments like this in the libraries and frameworks you use. Although it may seem unimportant, when someone else looks at your code, or when you return to your own code after a long time, you'll better understand what comes from where.

/**
 * Returns x raised to the n-th power.
 *
 * @param {number} x The number to raise.
 * @param {number} n The power, should be a natural number.
 * @return {number} x raised to the n-th power.
 */
function pow(x, n) {
  // ...
}

What a blessing ECMAScript is! That's all I have to tell. I'm sure I've made mistakes. I'm open to support and criticism. 😎 May your code be clean. 🤘🏻 Thanks for reading!

References

In this post I drew a lot of support from Jihad Al Khurfan's "Writing Clean JavaScript — ES6 Edition". I recommend reading his other posts too.