5.8 Boolean: true, false, and the Absence of Truthiness
Alright, let’s talk about everyone’s favorite binary decision-makers: Booleans. You’d think a type that can only be true or false would be the simplest thing in the world, a serene island of logic in a chaotic sea of data. And you’d be mostly right, which is why we’re going to spend our time on the weird, murky waters that surround that island—the places where language designers decided to get “creative.”
At its heart, a Boolean is the answer to a yes-or-no question. Did the user log in? true. Is this record valid? false. It’s the fundamental unit of logic that drives every if, while, and for statement in your code. Using anything else in those conditions is usually a party trick or a terrible idea. We’ll get to that.
The Two Hard Problems in Computer Science
There’s an old joke that there are only two hard problems in computer science: cache invalidation, naming things, and off-by-one errors. I bring this up because naming your Boolean variables is your first line of defense against writing incomprehensible garbage. Please, for the love of all that is holy, name them like they’re answers to a question.
// Terrible. What does 'flag' even mean? Is it set? Is it cleared? Who knows?
boolean flag = true;
// Bad. 'status' of what? A HTTP status? My emotional status?
boolean status = false;
// Good! It answers a question: "Is the user logged in?"
boolean isLoggedIn = true;
// Excellent! "Should we validate the input?"
boolean shouldValidateInput = false;
See the difference? The good names are self-documenting. They prevent you from writing a comment like // checks if user is logged in above an if (flag) statement, which is a sure sign your code is about to be haunted by the ghost of bad decisions past.
Truthiness and the Absence Thereof
Here’s where things get spicy. In some languages, non-Boolean values can be used in a Boolean context, like an if statement. This concept is often called “truthy” and “falsy.” It’s a convenient shortcut, but it’s a loaded gun pointed directly at your foot.
What is falsy? It’s the list of values that a language treats as false when it desperately wants a Boolean. The usual suspects:
false(obviously)null0(the integer zero)0.0(the float zero)""(an empty string)[](an empty array)
Everything else is truthy. This leads to concise, but potentially terrifying, code.
let userInput = document.getElementById('inputField').value;
let recentItems = [];
// Let's check for content!
if (userInput) {
console.log("You typed something!");
}
// This will only log if userInput is NOT an empty string.
if (!recentItems) {
console.log("There are no recent items.");
}
// This will log... wait, no it won't. An empty array is truthy in JavaScript!
// This is a classic pitfall. The condition evaluates to false because `recentItems` exists as an object.
// To check if it's empty, you'd need `if (recentItems.length === 0)`.
This “feature” is a source of endless bugs. Why is an empty array truthy? Who decided that? Probably the same person who thought == was a good idea. It’s a stark reminder that you must know your language’s specific rules on truthiness. Never assume.
The Perils of Implicit Conversion
This truthiness nonsense is built on implicit type conversion. The language sees you using a string in an if statement and says, “I got you, fam,” and secretly converts it to a Boolean behind the scenes. This is the programming equivalent of a friend “helping” by rewiring your house without telling you. Sometimes it works, but when it fails, it fails spectacularly.
Always prefer explicit comparison. It’s slightly more verbose but infinitely clearer and safer.
username = "" # This is a falsy empty string
# Don't do this:
if not username:
print("Please enter a username!")
# Do this instead. It's explicit and unambiguous.
if username == "":
print("Please enter a username!")
The first version works, but the second version shouts its intent to the reader and the compiler. It says, “I am specifically checking for an empty string,” not “I’m hoping the language’s quirky rules happen to do what I want today.”
The One True Way: Clarity and Explicitness
The best practice with Booleans is to be brutally obvious. Use them for their intended purpose: representing a true/false state. Avoid clever tricks with truthiness in professional code. The cognitive load it places on the next person (who might be you at 3 AM) is never worth the saved keystrokes.
When you need to check for the presence or absence of something, often a better way is to ask a more direct question.
// Instead of relying on a boolean 'isListEmpty', sometimes it's clearer to...
List<String> items = fetchItems();
if (items.isEmpty()) { // This method explicitly answers the question
System.out.println("The list is empty.");
}
// Instead of a vague 'hasError', be specific about what you're checking.
if (errorCode != 0) { // Explicitly check for the successful state
handleError();
}
Booleans are your friends. They are the bedrock of logic. Treat them with respect by naming them well and using them explicitly. And never trust a language that thinks an empty array is a true value. That way lies madness.