Tips on naming boolean variables - Cleaner Code

Published 10/3/2019

There is a convention to prefix boolean variables and function names with "is" or "has". You know, something like isLoggedIn, hasAccess or things like that.

But throughout my career I have seen and written code where this convention was just thrown out the window. So let's check out some of these edge cases.

As with all rules, there are exceptions and it might be better to go with that rather than enforcing a convention.

Boolean that verifies that every case is true

const XXX = users.every(user => user.isActive)

XXX will only be true if every user is active. How could we name the variable?

variable Any good? Reason
isUsersLoggedIn ๐Ÿคจ Grammatically incorrect
areUsersLoggedIn ๐Ÿค” Custom prefix
isEveryUserLoggedIn ๐Ÿ‘ Fits with Array.prototype.every
isEachUserLoggedIn ๐Ÿฅฐ Comes off more natural than "every" (depends)

Boolean that verifies that one of many cases is true

const XXX = users.some(user => user.isActive)

XXX will only be true if at least one user is active.

variable Any Good? Reason
isUsersActive ๐Ÿ™ Grammatically incorrect & ambiguous
isAtLeastOneUserActive ๐Ÿ˜ต Too wordy
isOneUserActive ๐Ÿคฅ Lie. This could imply that there is only one user active. Avoid confusion!!!
isSomeUserActive ๐Ÿ‘ Fits with Array.prototype.some
isAnyUserActive ๐Ÿค— Comes off more natural than "some" (depends)

Check out my e-book!

Learn to simplify day-to-day code and the balance between over- and under-engineering.

Avoid custom prefixes

We covered this in one of the examples before already, but there are more...

variable Any good? Reason
wasPaidFor ๐Ÿ˜ฃ Custom prefix
paidFor ๐Ÿค” No prefix
areBillsPaidFor ๐Ÿค” Custom prefix
hadHaveHadBeenPaidFor ๐Ÿ˜ถ Ok, I'm just joking at this point
isPaidFor ๐Ÿ˜Š

Affirmative names

variable Any good? Reason
isDisabled ๐Ÿง Non-affirmative
isNotActive ๐Ÿคฏ Just imagine !isNotActive
hasNoBillingAddress ๐Ÿ˜ž No need for "no"
isEnabled / isActive / hasBillingAddress ๐Ÿ˜ And use it like this !isActive to get the negative

The problem with non-affirmative names becomes most apparent when you have something like this

if (!account.isDisabled) {
  // ...

Just see how much easier this reads

if (account.isEnabled) {
  // ...

Finally let's take a look at a more complex example.

const isAnyUserOffline = users.some(user => !user.isOnline)

if (isAnyUserOffline) {
  // ...

While this works, because of the combination of some and !, it just takes a little more brain power to process this code. An alternative would be:

const isEveryUserOnline = users.every(user => user.isOnline)

if (!isEveryUserOnline) {
  // ...

It behaves the same and as long as the data set is small enough I would not worry about the small performance impact.

I am sure there is a lot I missed, but I think these are some of the more common cases.