Using single-letter variable names

When is it ok to use single-letter variable names?

The short answer

Generally single-letter variable names are bad for readability. However, there are a few exceptions where using single-character variable names is useful:

  • index variables when iterating over a list, e.g. i, n, k
  • some cases when the variable is only used within the space of up to three lines and it's clear what the name stands for

When iterating over a list

This is the most common use case for single-character variable names:

for (var i=0; i<list.length; i++){
    var item = list[i];

It's clear by convention that i is a list index.

If you have several nested loops, however, consider giving more descriptive names to the indices. That way you're less likely to confuse them in the future.

Error e, Event e

These are also common conventions and they usually don't cause any problems. However, I think it's slightly better to call them error and event instead.

Over longer bits of code it won't always be clear what e stands for.

Also, calling both these variables e causes confusion when having a catch (e) block inside an event handler.

While you don't gain a huge amount, you can avoid this extra bit of thinking by just giving them slightly more meaningful names.

x, y, z

If these are coordinates in coordinate system the names are perfectly descriptive, as they match the model you're describing.

If the specific meaning of the variables doesn't matter don't bother coming up with different names.

Short anonymous functions

You might have some code where you use an anonymous function to transform a value like this:

var prices = [50, 20, 30];
var discount = .9;, function (p) {return p * discount;});
// -> [45, 18, 27]

Personally I slightly prefer a longer variable name here:, function (price) {return price * discount;});

While it doesn't make a huge different it reads a little better to me. It also helps if you later decide to split off the function, so the prices array isn't directly next to the transformation function.