What (and How) to Name Things in Javascript
Naming conventions in JS generally focus on mechanics, ignoring semantics altogether. As part of a clean coding practice- that is, writing code for other engineers (including Future You) to consume- an ounce of clear writing is worth a pound of comments.
This post will share a some ideas and a simple rubric for how to name variables and functions in Javascript - descriptively - to help your code become self-documenting.
Basic Conventions for Naming in JS
The following are common rules for naming variables in JS, mostly having to do with formatting:
- -camelCase objects, functions, and instances
- -PascalCase is for constructors, classes (React components)
- -UPPERCASE_IS_SUGGESTED for global variables and constants
- -aVariableName should start with a letter
- -don't use single letter variable names, or scrunched abbreviations/concatenations
- -don't use leading or trailing underscores
- -acronyms should be all uppercased, or all lowercased
You can find a good list of these rules with examples in the Airbnb Style Guide on Github. While these are a good starting point, they don't really touch on writing self-documenting code.
Semantic Guidelines for Naming Variables
Where the common resources fall short is in what to name things, rather than how. Quoting Jeff Atwood on Twitter here: "There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors." And here's a "why" we would care about this, from the Airbnb styleguide: "Names are for readability, not to appease a computer algorithm."
Outside the trivial world of HackerRank exercises and job interviews, the way you name things has a lasting impact. While you're "in the zone" it's conceivable you'd keep the purpose of a throwaway variable in working (human) memory. But as you broaden the scope of work, you'll have to re-contextualize old variables in the context of new problems.
When naming things in production code, here are a couple heuristics that often fall by the wayside in tutorials/Stack Overflow/code-golfing "algo" challenges:
Be Specific
So let's start with one of the rules from above: "don't use single letter variable names, or scrunched abbreviations/concatenations." Unless you're programming firmware for a microwave or something (probably not in JS, yet) two things are likely:
- Your code will get transpiled before it hits production
- Your code will get minified before it hits production
This means you can name things with as much specificity as you need to accurately describe the what and the why of it. This means writing descriptive names in code won't hurt your bundle size. Your variable and function names will be long-gone by the time a client needs to process any code.
Variable names get longer with scope.
A narrower scope needs shorter names to convey full meaning. Take this simple mutation:
const clientList = [...];
const clientNames = clientList.map(client => client.name);
A common temptation in the map()
statement could be (c => c.name)
for brevity. But when you come back to it later, you have to slow down and contextualize what c
is all about. It's trivial here because the example is trivial. Naming the variable client
takes minimal extra work, and long-term prevents misunderstandings.
Complexity tends to grow exponentially. Don't try to flex on how "smart" you are as an engineer. When describing complex functionality, it pays to explain your thought process with variable names your mom could understand. If that's too difficult, consider it a red flag that your "thing" is doing more than one thing. Break it up.
If it takes a very long variable name to describe what's going on, it's a red flag you've got code that needs further abstraction. For instance, something like clientInvoiceDisclosureAcceptButtonClickHandler
in a React component says you should probably break out some subcomponents to narrow the scope. Perhaps a <ClientInvoiceDisclosure />
subcomponent with a button inside it, whose click handler is called something like acceptDisclosure()
.
The temptation in a case like this is to give this click handler a short but meaningless (or otherwise inscrutable) name and move on, rather than fix the bloat. This may be a sign of depression. It's basically saying your code is hopeless, so why bother? Fixing it now will speed you up in the future. Resist Deadline Driven Development.
Imply the Domain and the Return Value
A good name tells a person without domain-specific knowledge what to expect. I once found a variable called balances
that returned a boolean, in a React component I had never seen before. The person writing the component knew the use of balances
would be truthy or falsy, but that person was long gone.
To avoid the problem of domain knowledge and false assumptions, here's a simple pattern to follow for creating useful names in JS:
Item
domainNoun clientDetails
accountFlags
Flag
is, has, can, will, should hasDetails
shouldShowDetails
Function
verbNoun getDetails
shouldComponentUpdate
I've had feedback about "should" implying a function like shouldComponentUpdate
, rather than a boolean variable. The important part about shouldShowDetails
and shouldComponentUpdate
is the true
or false
return value, and not the implementation.
Conclusion
Descriptively and accurately naming variables like this can save you, Future You, and the next engineer a lot of headaches when revisiting your code out of context.
As a disclaimer, these are the (strongly-held) opinions of a React developer. I've applied a fair amount of the thinking from Clean Code by Robert Martin, from Java into Javascript. Otherwise a lot of these are lessons I learned through working on legacy code.
It seems there are very few resources specific to clean coding in Javascript. The general vibe seems to be that JS is moving too fast for time-tested best practices to be relevant, but that strikes me as throwing the baby out with the bathwater. However, I did find an excellent Github repo called Clean Code Javascript by Ryan McDermott, which is definitely worth a read!