< FrankJS />

How to Name Your Variables

Clearly, a very opinionated and subjective topic!

Here are some of my thoughts about this, as someone who works mainly in the front-end JavaScript space. When I say variables, I'm including functions as well, for our purposes here.

Use camel case form: addCoupon(), copyToLocalStorage() or disableSaleById().

Functions are actions, so try to use a verb in the name to help describe it. A verb and a noun together pair great!

For example:

  • clearTableData() clear the table data

  • isDarkMode() checking if dark mode is enabled

  • getHomeAddress() get the home address.

Avoid short names, that often may make sense to you now, but are still problematic. For example, I often see, and may use myself, inc, dec, etc. When your project grows in size, you take an extended break from viewing your code, or someone else tries to read it, the problem becomes apparent. Is inc increment, increase, or include?

What happens to your brain when you have to juggle "increasing" and "incrementing" in your app, while using a variable named inc? It explodes.

Another example is year and birthdayYear; code grows, plan now for this growth.

Also avoid taking this to the extreme, as unwieldy names like setExponentUsedForCalculation() are almost as bad.

For arrays, they are holding plural elements, so maybe instead of using animal, use animals.

Since booleans are like on/off switches they pair well with prefixes like is, has, and can.

Don't be lazy or rush! Your team will thank you.

... and don't forget to go back and refactor your code!

Frank J Santaguida, 2022