A Variable Should Have Clear and Obvious Naming

Coding languages like Python, JavaScript and C-Sharp do not care what you name your variable as long as it follows the languages rules. But you should. Variable naming is one of the most important and complex skills in programming. A quick glance at variable names can reveal which code was written by a beginner versus an experienced developer.

Real world coding requires spending a lot of time modifying and extending existing code rather than writing new code from scratch. Well labeled information is vitally important when returning to your old code or someone else’s code. Carefully considering your variable names will pay dividends in the future. For example let ourPlanetName = "Earth"; is more descriptive than let planet = "Earth";

Some good-to-follow rules are:

  • Use human-readable names like userName or shoppingCart.
  • Stay away from abbreviations or short names like a, b, c, unless you really know what you’re doing.
  • Make names maximally descriptive and concise. Examples of bad names are data and value. Such names say nothing. It’s only okay to use them if the context of the code makes it exceptionally obvious which data or value the variable is referencing.
  • Agree on terms within your team and in your own mind. If a site visitor is called a “user” then we should name related variables currentUser or newUser instead of currentVisitor or newManInTown.

Reuse or create? Some lazy programmers, instead of declaring new variables, tend to reuse existing ones. As a result, their variables are like boxes into which people throw different things without changing their stickers. What’s inside the box now? Who knows? We need to come closer and check. Such programmers save a little bit on variable declaration but lose ten times more on debugging. An extra variable is good, not evil. Modern JavaScript minifiers and browsers optimize code well enough, so it won’t create performance issues. Using different variables for different values can even help the engine optimize your code.