Skip to content

Instantly share code, notes, and snippets.

@uladzislau-stuk
Last active March 14, 2024 08:25
Show Gist options
  • Save uladzislau-stuk/cca7c72a9d54a6cf9dc4f1943b2d6ae5 to your computer and use it in GitHub Desktop.
Save uladzislau-stuk/cca7c72a9d54a6cf9dc4f1943b2d6ae5 to your computer and use it in GitHub Desktop.
The art of naming variables

The art of naming variables

Arrays

// bad
const fruit = ['apple', 'banana', 'cucumber']

// okay
const fruitArr = ['apple', 'banana', 'cucumber']

// good
const fruits = ['apple', 'banana', 'cucumber']

// great - "names" implies strings
const fruitNames = ['apple', 'banana', 'cucumber']

// great
const fruits = [{
    name: 'apple',
    genus: 'malus'
}, {
    name: 'banana',
    genus: 'musa'
}, {
    name: 'cucumber',
    genus: 'cucumis'
}]

Booleans

Booleans can hold only 2 values, true or false. Given this, using prefixes like “is”, “has”, and “can” will help the reader infer the type of the variable.

// bad
const open = true
const write = true
const fruit = true

// good
const isOpen = true
const canWrite = true
const hasFruit = true
const wasEgg = true
const eatAble = true
const haveCustomFilters = true
const hasCustomFilter = true
const areCustomFiltersApplied = true
const isCustomFilterApplied = true

Functions

What about predicate functions (functions that return booleans)?

const checkHasFruit = (user, fruitName) => (
    user.fruits.includes(fruitName)
);
const hasFruit = checkHasFruit(user, 'apple')

Functions should be named using a verb, and a noun. When functions perform some type of action on a resource, its name should reflect that. A good format to follow is actionResource. For example, getUser.

// bad
userData(userId)
userDataFunc(userId)
totalOfItems(items)

// good
getUser(userId)
calculateTotal(items)

A common convention for transforming values is prefixing function names with to

toDollars('euros', 20)
toUppercase('a string')

Articles

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment