DEV Community

Cover image for Clean Code 101: Variable Naming Conventions - Part 1
MohitSinghChauhan
MohitSinghChauhan

Posted on • Updated on • Originally published at mohitdotexe.hashnode.dev

Clean Code 101: Variable Naming Conventions - Part 1

Humorous image of software quality estimation as a count of how many expletives<br>
you shout when reading code

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:

const yyyymmdstr = moment().format('YYYY/MM/DD');
Enter fullscreen mode Exit fullscreen mode

Good:

const currentDate = moment().format('YYYY/MM/DD');
Enter fullscreen mode Exit fullscreen mode

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:

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

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

  // do more stuff

  // what was l again?
  dispatch(l); 
});
Enter fullscreen mode Exit fullscreen mode

Good Example:

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

locations.forEach(location => {

  // do stuff

  // do more stuff

  dispatch(location);
});
Enter fullscreen mode Exit fullscreen mode

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:

getUserInfo(); 
getClientData();
getCustomerRecord();
Enter fullscreen mode Exit fullscreen mode

Good:

getUser();
Enter fullscreen mode Exit fullscreen mode

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 and ESLint can help identify unnamed constants.

Bad:

// What is 86400000 milliseconds for? 
setTimeout(blastOff, 86400000);
Enter fullscreen mode Exit fullscreen mode

Good:

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

setTimeout(blastOff, MILLISECONDS_PER_DAY);
Enter fullscreen mode Exit fullscreen mode

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:

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

saveCityZipCode(
  address.match(cityZipCodeRegex)[1], 
  address.match(cityZipCodeRegex)[2]
);
Enter fullscreen mode Exit fullscreen mode

Good:

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

const [, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);
Enter fullscreen mode Exit fullscreen mode

Avoid Unneeded Context

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

Bad:

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

function paintCar(car, color) {
  car.carColor = color;
}
Enter fullscreen mode Exit fullscreen mode

Good:

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

function paintCar(car, color) {
  car.color = color; 
}
Enter fullscreen mode Exit fullscreen mode

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:

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

  // ...
}
Enter fullscreen mode Exit fullscreen mode

Good:

function createMicrobrewery(name = 'Hipster Brew Co.') {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

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 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 ❤️

Top comments (12)

Collapse
 
giovannimazzuoccolo profile image
Giovanni Mazzuoccolo • Edited
const address = 'One Infinite Loop, Cupertino 95014'; 
const cityZipCodeRegex = /^,([^, \]+) ([^, \]+)(?: ([^,\s]{5}))?$/; 

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

This code doesn't work. The regexp is not correct - Unmatched ')' - and the array destructuring got the wrong words.

This is the correct one

const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^([^,]+),\s*([^,]+)\s+(\d{5})$/;

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

Fell free to check it on this codesandbox

Collapse
 
hayley_grace profile image
Hayley Grace

Well written article :)

Collapse
 
mohitsinghchauhan profile image
MohitSinghChauhan • Edited

Thank you for your kind words.

Collapse
 
chiragagg5k profile image
Chirag Aggarwal

The only thing harder for programmers to do than getting a life is thinking of variable names

Collapse
 
mohitsinghchauhan profile image
MohitSinghChauhan

Lol! So true.

Collapse
 
venkatlohithdasari profile image
Venkat Lohith Dasari • Edited

Amazing Article buddy!! Its really useful for someone like me who is working on open source projects, it helps Construct project and codebase in such a way that other can understand it! Thanks

Collapse
 
onlinemsr profile image
Raja MSR

One point that I liked from the post is the use of meaningful and pronounceable names for variables. I think this makes the code more readable and understandable.

Collapse
 
abdrcao profile image
Antonio Belo

Great article! Thanks

Collapse
 
mohitsinghchauhan profile image
MohitSinghChauhan

Thanks, Stay Tuned, more to come.

Collapse
 
tensorprogramming profile image
Tensor-Programming

Excellent article, though I'd like to insert a caveat regarding the 'clean code' idea.

Despite reading Uncle Bob's acclaimed book and your insightful piece my experience tends to be a bit different. The term 'clean' in the context of code can be quite ambiguous and interpreted differently. Standard definitions for clean code can often be somewhat self-contradictory. For example, some may view the use of singletons as enhancing comprehension, yet they may not necessarily aid maintainability or performance over time. Engineering is a matter of striking a balance, and as a team, we need to grasp and discuss these trade-offs, keeping the project requirements in mind.

Let's look at the spread operator and iterators in JavaScript as a case in point. Generally, it's viewed as 'cleaner' to use these tools. However, if you're working with large data sets, you may encounter performance issues due to memory allocation and how the garbage collector operates.

In this context, the concept of 'clean' code clashes with the reality of the language. The ideal clean code would strike a balance between readability and performance. However, in this situation, even if readability is improved (subject to individual interpretation), performance significantly deteriorates.

This underscores why principles like clean code should be viewed as flexible guidelines rather than rigid rules. No matter how straightforward the idiom might appear, there's always an outlier that challenges it.

Collapse
 
laansday profile image
Tony Do

You’re inspired from the actual book Clean Code right? I can tell from your very first sentence

Collapse
 
arocha profile image
Nefario313

Uncle Bob have more interesting ideas about variables names. Short name vs long names and when to use them.