Monday, January 20, 2025

Variable Naming Conventions in JavaScript

Have you ever noticed that every programming language seems to have its own set of naming conventions? While some languages have a lot in common, others just seem to exist in a world of their own. I’d like to share with you some naming conventions for JavaScript. Along the way, I’m going to interject some info on where various standards originate from and why they are important. In fact, let’s start there.

Why Naming Conventions Are Important

Let’s clarify one point before continuing. Naming conventions, like any programming standard, is not necessary for writing code that runs just fine. In fact, it’s entirely within the realm of possibility to have a program developed by a fifteen year old rebel, with no regard for any conventions or standards that wipes the floor with the code written by a team of seasoned experts. Nonetheless, in business, where it is common for teams to work on a piece of code or for several people to work with it successively during the life of an application, it is of great benefit to everyone involved that the code be written in some sort of uniform fashion. That not only includes naming conventions but also style conventions, best practices, and other systems that the business or team might enforce. Using standardized naming conventions helps make code easier to read for both the writer and for other programmers. Trust me, look at something you wrote a year ago and you’ll need plenty of help remembering what your code does! Readability of code is important because it means less time is spent trying to figure out what the code does, leaving more time to fix or modify it. Documentation also helps, but that’s a whole other story!

 

What’s in a Variable Name?

A variable name actually refers to an identifier. Hence, it may identify anything that can be stored in memory and referenced later. This may include a class/object, a path, a primitive, a function/method, filesystem item, a database, you name it. A complicating factor is that different variables are used in different ways and thus possess very different qualities. Consider the differences between constants, singletons, static, global and private scope, scalars, arrays, collections, etc… Should their names reflect some of these traits? In fact, in many cases, they should. We’ll see how in a minute.

Variable qualities aside, the most important thing you can do is to choose an identifier name that is both meaningful and correct. For instance, if your program deals with customer accounts then your naming choices should reflect that (e.g., customerName, accountDetails). Your names may even need to be more specific, if for example you have different types of customers, such as online and in person. It’s true that names can get to be quite long, and that can make a line of code accordingly lengthy. How long? Try these real application variable names on for size!

VirtualMachineDeviceRuntimeInfoVirtualEthernetCardRuntimeStateVmDirectPathGen2InactiveReasonOther
function SelectAllUsersWhereDobIsGreaterThan1980AndIsMaleOrderByNameAndAge() {}
var instrumentAreaDockWidgetVisibilityFollowsChildPresence;

Certain languages, like C and C++, seem to like names that can be as short as one letter. This is also true of JavaScript, where optimization and obfuscation might lead one to choose names that are as succinct as possible. In my opinion, a longer name that sums up the identifier accurately is preferable to a shorter name that shortens the overall script length but is ambiguous.

 

Global versus Private Scope

Let me just preface this section by saying that global variables can be trouble and are best avoided whenever possible. The exception to this rule is constants. These are variables that are hard-coded, for all intents and purposes, and never change throughout the life of the script or application. Funnily enough, constants are not supported in JavaScript. However, there is nothing stopping you from creating your own facsimile. The trick is to know which variables are not to be changed. That makes the naming convention all the more critical. Constants traditionally are written in upper case with underscores between words:

var SERVER_URL = 'http://localhost/';
var BUSINESS_EMAIL_FOLDER = 'FOSS IMPORT';
var BOOKS_FICTION_INDEX   = 1;

Most programmers worth their salt know instinctively not to mess with variables written in this style.

If you have to use global variables, you definitely want to identify them as such. Some people like to preface them with a ‘g’ for global. There is an alternative in JavaScript because all globally scoped variables are appended to the window object array. Hence, any variable created outside of a function or object, whether using the ‘var’ keyword or not, is appended to the global window namespace. That being the case, why not explicitly add them?

//GOOD:
var gGlobalVar        = 'I am global';
//NOT SO GOOD (don't forget the var!):
gAnotherVar           = 'I am also global';
//BEST:
window.defitelyGlobal = 'I am definitely global!'; 

The benefit of appending global variables to the window namespace is that you can even create global variables from within functions or objects!

While JavaScript does not officially support privately scoped variables, it is nonetheless easy enough to create them, since any variable created within a function or object is scoped to that function or object. There are no hard-and-fast rules for identifying privately scoped variables since they are what you could call the default. However, some people like to prefix them with an underscore when part of a function that is to be instantiated as an object:

var Person = function() { 
    //defaults
    var _age  =  0,
        _name = 'John Doe';

    this.initialize = function(name, age) {
      _name = _name || name;
      _age  = _age  || age;
    };
    
    if (arguments.length) this.initialize();
    
    //public properties. no accessors required
    this.phoneNumber = '555-224-5555';
    this.address     = '22 Acacia ave. London, England';
    
    //getters and setters
    this.getName     = function()      { return _name; };
    this.setName     = function (name) { _name = name; };
    
    //public methods
    this.addBirthday = function()      { _age++; };
    this.toString    = function()      { return 'My name is "+_name+" and I am "_age+" years old.'; };
}; 

 

Conclusion

Some people like to add another prefix to their variables that denotes its type, such as str for string, i for integer, fl for float, etc. That practice came from Visual Basic’s Hungarian variable naming style. While including type info in a strongly typed language makes little sense, it *may* be of some benefit in a loosely typed language like JavaScript. Personally, I would advise you to stick the following the few simple rules outlined here. That in itself will make your code far more readable and maintainable.

Rob Gravelle
Rob Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured