Write Cleaner Code in JavaScript #1 Variables

The Atypical Developer
3 min readSep 10, 2022

--

Why developers are so crazy about using this term? What does “clean code” actually stands for? I’ll try to address it all in this article.

As a developer, one of my responsibility is to write the code. The code has it’s purpose, it has to do something and it has to work. Everytime I start sketching something in the IDE I’m questioning if the written piece is going to be understandable by other developers, are the variable names are good and all sorts of other existential questions.

What do I want to achieve when writing a clean code? My focus is to make sure that the code:

  • is easy read
  • can be reused
  • is easy to be refactored by others

You should care about the code itself and how it’s written, instead only worrying does it work or not. The following concepts are recommendations adopted from Robert C. Martin’s book Clean Code.

Variables

Naming variables

I used to spend a lot of time on figuring out how to name variables so they’re understandable. Use camelCase for identifier names (variables and functions). All names should start with a letter.

// Don't ❌const random = "example@gmail.com";
const myArray = ["Volvo", "Mercedes", "Audi"];
// Do ✅const email = "example@gmail.com";
const cars = ["Volvo", "Mercedes", "Audi"];

Use searchable values

// Don't ❌// no one knows what are these numbers
const workingDaysInMonth = () => {
return 5 * 4;
}
// Do ✅// your hardcoded vars should be capitalized
const WEEKS_IN_MONTH = 4;
const WORKING_DAYS = 5;
const workingDaysInMonth = () => WEEKS_IN_MONTH * WORKING_DAYS;

Avoid adding unneded context

// Don't ❌const cars = [ 
{
carBrand: "Volvo",
carPrice: 100,
},
{
carBrand: "Mercedes",
carPrice: 125,
}
];
const updatePrice = (price) => {
return cars.forEach((car) => car.carPrice + price)
}
// Do ✅const cars = [
{
brand: "Volvo",
price: 100,
},
{
brand: "Mercedes",
price: 125,
}
];
const updatePrice = (price) => {
return cars.forEach((car) => car.price + price)
}

Avoid Mind Mapping

Avoid using the variables in which only the author knows what they mean.

// Don't ❌const cars = [ 
{
brand: "Volvo",
price: 100,
},
{
brand: "Mercedes",
price: 125,
}
];
// only I know what that 20 means
cars.map((car) => car.price * 20);
// Do ✅const CURRENT_TAX = 20;cars.map((car) => car.price * CURRENT_TAX);

Use default parameters

// Don't ❌const navigateToPath = (path) => {
return path || "/random-path";
}
// Do ✅const navigateToPath = (path = '/random-path/) => {
///...
}

It might take you some time to get used to these, especially if you’re going to apply these practices in larger codebases. Although, in the long run, your code will be easier to read, scale and refactor.

In the next part you’ll find clean code principles for objects.

PS. If you prefer the video version of it, you can find it here:
Youtube

--

--