DEV Community 👩‍💻👨‍💻

Jesse M. Holmes
Jesse M. Holmes

Posted on

How Do You Name Your Boolean Variables?

I've seen some absolutely confounding names in recent code reviews. Sometimes you need to know if Godzilla exists! Do you:

const godzillaExists;
const doesGodzillaExist;
const godzilla;
Enter fullscreen mode Exit fullscreen mode

Maybe it's more specific:

const godzillaExistsInStore;
const godZillaInStore;
const hasGodzillaBeenStored;
Enter fullscreen mode Exit fullscreen mode

Top comments (8)

Collapse
 
gsto profile image
Glenn Stovall • Edited on

I prefer the first example in both cases. Specificity depends on the context. Does the function care about the "store" or not? Could Godzilla exist somewhere else, heaven forbid?

My go-to is to default to writing booleans in a way that makes them read more sentence-like in context. For example:

if ( godzillaExists && mothraExists ) {
  doBattle(godzilla, mothra) 
}
Collapse
 
dmfay profile image
Dian Fay

Hungarian notation is dead and good riddance to it, but formulating boolean names as isX or hasX does a lot for clarity.

Collapse
 
610yesnolovely profile image
Harvey Thompson • Edited on
var hasGoodPoint = true;
var isMyConvention = true;

Also, I prefer not to pass booleans to (typically multi-argument) functions unless they are obviously expecting true or false (ie. property methods), so typically "can" or similar named functions:

This is okay:

canPost(true);

But this is not so good:

someMethod("Thing", true);

Some languages have named arguments, so in that case it'd be better to say:

someMethod("Thing", canDelegate=true);

Alternatively use enums:

someMethod("Thing", Delegation::Allowed);
Collapse
 
jckuhl profile image
Jonathan Kuhl

usually something that makes grammatical sense paired with if

if(userExists && userHasValidCredentials) { handeLogin(user) }

I'm also not worried about long variable names because VSCode fills them in for me, and most editors do that for you.

Collapse
 
aligear profile image
aligear

I usually use a variable with is as prefix, like

let isUserLogged = false;
Collapse
 
databasesponge profile image
MetaDave 🇪🇺

For Ruby, and the humble question mark.

def intersects_with?(other)
  return false if empty? || other.empty?

  (self & other).any?
end

How would you feel about godzilla?

Collapse
 
satyanx1 profile image
satyanx1

At least they all follow camel casing

Collapse
 
pcrunn profile image
Alexander P.

In that case I wouldn't use a boolean but an object. To check if it exists, I'd check if it's null or not.

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.