// 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 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
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')