loading...
Cover image for How JavaScript Variables Should Be Named

How JavaScript Variables Should Be Named

codeartistryio profile image Reed Barger Originally published at reedbarger.com on ・3 min read

Let’s talk about how your JS variables should be named.

We’ll cover what the language doesn’t allow you to do and how you should name variables so you and other developers can easily know what they contain:

Case-Sensitive

Let’s start with a question—I’ll create three variables ‘name’, one lowercase, one capitalize and one with all caps:

const name = "Jane";
const Name = "Mark";
const NAME = "Fred";

Are these the same variable? What do you think? Will I get an error when I console log each of these variables?

console.log(name, Name, NAME); // "Jane" "Mark" "Fred"

These are all valid variables name, despite their different. We can see that variables, first of all, are case-sensitive. They can have the same sequence of letters, but casing matters.

Self-Descriptive

Second, variable names should be clear about what they contain.

Let’s say we are looking at someone else’s code and see this:

let newValue = `${value1} ${value2}`;

Do you know what’s taking place? Two values are being added, but you have no idea what or what data type they are.

Now if the names are improved, for example:

let fullName = `${firstName} ${lastName}`;

We see and understand exactly what’s going on. We can infer from these names, as well as that they are strings and fullName will be a string as well. So variable identifiers should be self-descriptive and not require comments for others to know what they hold.

Third, variables should in most cases be written in camel syntax, where the first word in the name lowercase, and the rest uppercase:

let firstname;
let first_name;
let FIRSTNAME;
let FIRST_NAME;
let firstName;

Which of these are correctly written in camel case? Just the last one.

The camel case convention is the most important rule to remember when writing JS variables, but there are other helpful conventions, meaning ones that are helpful to follow because of what they signal to developers, but are not required by the language itself.

Boolean naming convention

Since JS is a loosely typed language, meaning any variable can contain any data type, the way we name variables can tell other developers what type of data it should hold.

Let’s say we control whether a modal or popup is visible with a variable. If a variable is true, it’s visible, if false, it’s not.

To tell other developers exactly what this does, we could have a variable called isModalVisible. Why prefix it with ‘is’? Not only does it tell us it contains a boolean, but is easy to read in conditionals. If we want to do something if the modal was visible, our code would be this:

if (isModalVisible) {
  // do this
}

Now this conditional reads just like a sentence. The closer we can get our code to reading like it was plain instructions, the better.

To figure out the prefix, put the variable in a conditional and read what it says. Usually variables that hold booleans are prefixed with ‘is’, ‘has’:

let isLoading;
let hasPosition;

Constant naming convention

Another valuable convention is for variables whose values should never change. We already know that we have the const keyword to create variables that can never be reassigned. However, for variables whose value should never be changed by other developers manually, either, we write the variable names in all caps.

For example, we might have the hex color red saved in a variable to easily reference it. The color red is never going to change and doesn’t need to be updated so we can use all caps:

const COLOR_RED = "#F00";

And note that unlike camelcase, for all caps constants, we separate words in the identifier with underscores

Summary

Let’s review:

  • Variables are case-sensitive
  • Their names should be self-descriptive; we should know exactly what they hold based on it’s name, and from that have an idea about what data type that is
  • Most every JS variable you write will be in camelCase
  • Since variables can hold anything and can be changed easily, we use conventions to give more information to other developers,
  • Like using ‘is’ or ‘has’ to prefix variables that hold booleans
  • And using all caps for variables that hold values that should never change

Want To Become a JS Master? Join the 2020 JS Bootcamp

Join the JS Bootcamp Course

Follow + Say Hi! 🎨 TwitterInstagramreedbarger.comcodeartistry.io

Posted on by:

codeartistryio profile

Reed Barger

@codeartistryio

Sharing artful coding skills that fuel the life you want to live @ CodeArtistry.io 🎨

Discussion

markdown guide
 

Yes, but first_name is much easier for the eye and brain to read and comprehend than firstName and I am starting to really doubt this "best practice"/convention....

Choose a style and be coherent in your project would be my advice

 

That may seem logical but perhaps not true, there was a research paper which showed:

An empirical study of 135 programmers and non-programmers was conducted to better understand the impact of identifier style on code readability. The experiment builds on past work of others who study how readers of natural language perform such tasks. Results indicate that camel casing leads to higher accuracy among all subjects regardless of training, and those trained in camel casing are able to recognize identifiers in the camel case style faster than identifiers in the underscore style.

cs.loyola.edu/~binkley/papers/icpc...

 

Use what suits you best and be consistent...

 

Using firstName isn't a best practice, it's a naming convention. Adhering to naming conventions, now that's a best practice. The benefit there is that you don't have to continuously mentally switch when reading various people's code, which increases communication speed and reduces the likelihood for errors.

 

Choosing snake_case will make your JavaScript code inconsistent - the JS standard library uses camelCase as well as the rest off ecosystem, so the code will end up having mixed conventions.

 

I agree, just keep it consistent over the whole project.

An intern of mine once told me, his Teacher had told him, that methods MUST ALWAYS be capitalized (ie: MyMethod()) otherwise it was a sign of a BAD programmer.

So yea, everybody has different opinions on this, but the one thing shared across most people is to be consistent with your namings.

 

Totally agree. I switched to a different naming convention a while ago, where the words are separated by an underscore, and they are in a progressive order from the most generic to its most detailed specification. E.g.
name_full, name_first, name_last
url_spreadsheet, name_sheet
object_employee
array_users
condition_valid_input
I rarely had problems misunderstanding my code ever since

 

Not sure array_users is a good idea. What if you change the type to another iterable type? Do you rename all occurrences of the variable?

Well, why would you change the iterable type in first place? (Not rethoric question)
And, in that case, would it be so complicated to make a replace all in the code editor?

Maybe you'd like to have an object instead of an array to access users by their ID, or even better a Set. Heck maybe one day you wake up and think a linked list is the perfect solution.
Replacing the variable name per-se is not a problem, but it's still additional overhead.
Wouldn't it be better to name it like usersList and be done with its name forever?

Absolutely right, but I'd like to stress that the core of my point is that the order should be hierarchy-based, from the most generic to the most specific.
Sure, first_name is more readable at first glance (btw only because of the english order of words), but that's just because you are not yet used to this system. From my experience, as you get used, it helps a lot to know immediately that name_first and name_last are names, and gives the naming a lot more consistency.
So, in the list case I'd use "list_users" : you immediately know that is a list (from the variable "users" we infer that it might be a list just arbitrarly), and that has type-relatives in "list_admins" and "list_employees"

 

For me first_name reads more natural than name_first, I need to be able to put it in a sentence. But that is just me, choose whatever fits you best...

 

I do agree to choose which one suits you and your team the best.

I don't agree that first_name is easier to read and comprehend. Lol. I always hated writing and reading variables or method names like that. Lol.

So let's go with just use a style that is consistent with your team. Though one could argue that with open source projects that using a style that is consistent with what you usually see with the language you're working on could help potential collaboration. Though being consistent with a style guide will help the most

 

Just follow the built-ins…

classList, getElementsByClassName // method
Array, Object, ArrayBuffer // class
Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER // constant
 

I'm currently in a project where custom methods are underscored, used with standard methods. It's an eyesore.

 

You left off plural names for arrays. If I see kittens I instantly know that it is an array of objects. if I see kittenNames then I know it is an array of strings. Boolean, String, Number, Object, these types only contain ONE of any thing. It's possible the variable could be a Set but most codebases use those very rarely. So it's a very safe bet to assume "plural == array".

 

I've been taking some tutorials from laracasts.com. He doesn't believe in comments, and lets the code speak for itself. (which I disagree with but I get where he's coming from)

So you'll see things like:

isThisAnApple('fuji');

and 

$teacher = HighSchool->10thGrade->MathClass->Teacher;
$teacher->gradePapers();

He treats his code like it's english. And it really is elegant naming.

 

fingers crossed that ide's get smart enough to present the code however makes the most sense to the consumer
send me the ast and let the ide figure it out

 

great write up. Pop quiz: When encountering "_" prefix on variables; what does this notation represent.

Bonus: Explain the importance of "g_" prefix.

 

I agree with and follow all these recommendations. I find no spell check issues using camel case.

 

Writing proper variable names (in any language) is an art. An art everybody should learn.

P.S: Small typo: These are all valid variables name, despite their different.

 

The two hardest problems in computer science are naming, cache invalidation and off by one errors.

 

I would argue that variables such as loop counters etc. do not need meaningful names

 

I have been using camel case for quite some time now and I feel that is best practice for me with naming conventions. I have tried the other naming conventions but I feel camel case is best.