Clean Code 101: Variable Naming Conventions - Part 1
Tags: javascript, beginners, cleancode, webdev
Published: 2023-07-23 21:27:28

![Humorous image of software quality estimation as a count of how many expletives
you shout when reading code](https://www.osnews.com/images/comics/wtfm.jpg)

What's the best way to measure how clear and understandable code is? Simple - count the "WTFs/minute". When reading confusing, messy code, you can't help but think "What the heck is this doing?" more often. Those WTF moments add up fast, wasting time and energy trying to understand bad code.

So, what causes those WTF head-scratching moments? Usually it's code that ignores clean coding principles:

* Poorly named variables/functions
    
* Overly complex conditionals and loops
    
* Deep nesting and sprawling functions
    
* No comments explaining the intent
    
* Inconsistent formatting
    

Code like this takes longer to understand. It's a pain to update or fix bugs. Other developers on your team will struggle with it too.

Writing clean code minimizes "WTFs" and speeds up development. Your future self will thank you when revisiting old code. Fixing bugs and adding features in clean code is much easier.

> Let's start writing JavaScript that brings clarity, not confusion! The less "WTFs-per-minute", the better!

## Variable Naming 101

Variable naming is one of the most important skills in programming. The names we choose for variables can make our code either very readable and maintainable or extremely confusing. Here are some best practices for naming variables in JavaScript:

## Use Meaningful and Pronounceable Names

Variable names should clearly convey what data they contain or what purpose they serve. Avoid single-letter variables like `x` or abbreviated names that may be unclear like `nmd`.

**Bad:**

```js
const yyyymmdstr = moment().format('YYYY/MM/DD');
```

**Good:**

```js
const currentDate = moment().format('YYYY/MM/DD');
```

Variable names should also be pronounceable to aid in code review and discussion. For example, `currDate` is more pronounceable than `crDt`.

Avoid ambiguous names that force the reader to mentally map what the data represents.

**Bad Example:**

```javascript
const locations = ["Austin", "New York", "San Francisco"];

locations.forEach(l => {
  // do stuff

  // do more stuff

  // what was l again?
  dispatch(l); 
});
```

**Good Example:**

```javascript
const locations = ["Austin", "New York", "San Francisco"];

locations.forEach(location => {

  // do stuff

  // do more stuff

  dispatch(location);
});
```

The second example is much clearer in conveying we are iterating through an array of locations.

Use variable names like `location` rather than short names like `l` to avoid mental mapping. Your co-workers will thank you!

## Use the Same Vocabulary for the Same Types

Try to use a consistent vocabulary across your codebase for variable names representing similar data types or concepts. For example, always refer to a user object as `user` instead of sometimes using `user`, `userInfo`, `client`, etc.

**Bad:**

```js
getUserInfo(); 
getClientData();
getCustomerRecord();
```

**Good:**

```js
getUser();
```

This improves readability and avoids confusion when working on different parts of the codebase.

## Use Searchable Names

We read code much more than we write it. Ensure your variable names can be easily searched to aid in understanding the code later. Avoid generic names like `data` or `object` that reveal little about what's inside them.

Tools like [buddy.js](https://github.com/danielstjules/buddy.js) and [ESLint](https://github.com/eslint/eslint/blob/660e0918933e6e7fede26bc675a0763a6b357c94/docs/rules/no-magic-numbers.md) can help identify unnamed constants.

**Bad:**

```js
// What is 86400000 milliseconds for? 
setTimeout(blastOff, 86400000);
```

**Good:**

```js
// Declare as a capitalized named constant
const MILLISECONDS_PER_DAY = 60 * 60 * 24 * 1000; 

setTimeout(blastOff, MILLISECONDS_PER_DAY);
```

## Use Explanatory Variables

For complex operations, use intermediate variables to aid readability. Avoid forcing the reader to mentally map what a block of code is doing.

**Bad:**

```js
const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^,([^, \]+) ([^, \]+)(?: ([^,\s]{5}))?$/; 

saveCityZipCode(
  address.match(cityZipCodeRegex)[1], 
  address.match(cityZipCodeRegex)[2]
);
```

**Good:**

```js
const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^,([^, \]+) ([^, \]+)(?: ([^,\s]{5}))?$/;

const [, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);
```

## Avoid Unneeded Context

Don't repeat class or object names in variables. The context is usually obvious from nearby code.

**Bad:**

```js
const Car = {
  carMake: 'Honda',
  carModel: 'Accord',
  carColor: 'Blue'  
};

function paintCar(car, color) {
  car.carColor = color;
}
```

**Good:**

```js
const Car = {
  make: 'Honda',
  model: 'Accord',
  color: 'Blue'
};

function paintCar(car, color) {
  car.color = color; 
}
```

## Use Default Parameters Instead of Conditionals

In ES6, default function parameters can replace conditional logic. Be aware this only works for `undefined` values - other falsy values like `''` or `0` will not be replaced.

**Bad:**

```js
function createMicrobrewery(name) {
  const breweryName = name || 'Hipster Brew Co.';
  
  // ...
}
```

**Good:**

```js
function createMicrobrewery(name = 'Hipster Brew Co.') {
  // ...
}
```

Following these variable naming best practices will make your code clearer and more maintainable for both yourself and other developers. Put care into the names you choose!

### Ending Note :)

Following these general guidelines will help you to reduce "WTFs" and improve your code's clarity.

But there's more we can do to level up our clean coding skills. In the next parts of this series, we'll tackle topics like:

* Common code smells to avoid
    
* Refactoring techniques
    
* Clean architecture patterns
    
* Writing robust tests
    
* Automating code linting
    

See writing clean code is a journey. But by incrementally adopting principles like those covered today, we put ourselves on the path to mastering this critical skill.

If you want to go super in-depth, give a read to very famous book [Clean Code: A Handbook of Agile Software Craftsmanship](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882) by Robert C. Martin (Uncle Bob), which also inspired this blog.

The more we value readable, maintainable code, the better experience we create for our users, teammates, and future selves. Take Oath to get onward with clean code!

Happy Coding ❤️