Fundamentals

How to Name Variables and Functions

"There are only two hard things in Computer Science: cache invalidation and naming things." – Phil Karlton

Naming things sounds incredibly basic. Surely one can rip a dozen variables names of the top of their head with hardly a thought. However, well written software is self-documenting, providing insight into how the code works. Naming variables and functions in such a way that other developers can understand your code (or even you a few months from now) is a valuable skill.

How to Name Variables

Variables are essentially containers, so you should declare them in such a way that their contents are known without peering too deeply inside. Variables should be nouns and they should describe what they hold; they should be short but avoid abbreviations that could obscure their meaning.

Good examples:

let armor = 10;
let heightInInches = 74;

// make the variable plural to allude to array or list
let weapons = ["blaster","thermal detonator","knife"];

// boolean values should convey the state, and should make sense in an "if" statement
let isAlive = true;

Bad examples:

let a = 10; // what does "a" mean? what is the context?
let wkdy = "Th"; // abbreviation unnecessarily increases mental work to understand code
let peopleArray = ["Bob", "Patty"]; // "Array" is unnecessary in the function name

Sometimes variables are named a certain way by convention. Using camelCase vs using underscore_naming is a matter of convention. Using i in for loops is another convention. Follow the convention in use in the code you’re working with over favoring a new approach. That way the code will make sense to those that follow after you.

// for loops often follow this convention, with the variable "i" used as a counter
for(let i = 0; i < total.length; i++) {
    // some code
}

When a naming convention has become so widely used that it’s a defacto standard (as in the for loop above), feel free to use the convention instead more meaningful names.

How to Name Functions

Functions do things. They perform actions. So you should use verbs in function names to indicate an action is occurring when they are called. Function parameters should be short yet descriptive.

Good examples:

function getAge(name) {
    // some code
}

function calculateTotal(number1, number2) {
    // some code
}

function repaintCanvas(interval) {
    // some code
}

Bad examples:

function first() {
    // some code
}

function arrange(a, b) {
    // some code
}

function empty() {
    // some code
}

Taking a little extra time to name variables and functions in a self documenting way will help reduce the amount of comments you’ll need in your code and will reduce friction whenever anyone needs to maintain your code (including you). Take time to think through the names you choose – your future self will be glad you did!