Sometimes I come across stuff that seemed like it should have been obvious, but wasn't. This post is all about variable names in JavaScript, and specifically valid values for the first character.

I recently found a variable in code that was a single character and an underscore '_'. Can you do that? We'll get to that later.

The First Character in a Variable Name

Most of the time when you create a variable name, you'll want to give it some descriptive name, like this:

view plain print about
1let myVar = "Some Value";

Variable names are often in camel case, and start with a letter. You've probably all dealt with that.

Sometimes, such as when creating classes in TypeScript, we create a private variable and prepend an underscore to the name. Here is a simple JS Sample:

view plain print about
1let _myPrivateVar = 'Some Private value';

This is a perfectly valid variable name. The underscore can be one of the first characters in the variable name.

You can also use a dollar sign:

view plain print about
1let $myDollarSignVar = 'Some Dollar Sign Value';

This works perfectly too.

The Length Minimum

To answer my earlier question, there is no length minimum to a variable name, so a variable with just an underscore works perfectly. As does a variable with a dollar sign:

view plain print about
1let _ = 'Foo';
2console.log(_);
3
4let $ = 'Bar';
5console.log($);

Play with that here.

I do not recommend writing a variable name with a single character, because it is not very descriptive, however a lot of minimizers will strip out as many characters as possible in order to compact your code.

Why can't you use a number as the first character in a variable name

We've covered three options for the first character of a variable. A letter, an underscore, and a dollar sign. Can you use a number? Nope! That won't work.

The reason you can't use a number is because of how the code is executed deep under the hood. String literals must be enclosed in quotes. But, number literals are not enclosed in anything. When the interpreter (or compiler) encounters a number, it would have no way to know if it was looking at a variable or a numeric literal. As such, I've never worked with a language that allowed numbers as the first character of a variable name.

One of my earlier consulting clients actually named their database tables with numbers in them and I had a bunch of trouble accessing data. I think at the time I was coding in VB.NET. I don't remember specifics, but I had to access tables and columns using object array notation, similar to this:

view plain print about
1object['1Table']

I sent the client an email about how compilers work, and why this was a bad idea. They sheepishly reverted the change a few weeks later because it was causing so many issues across the org for all programmers integrating with the system.

Fun times!