Skip to main content

Building Blocks in JS

Data types in depth - Booleans

Whether you’re building a complex web application or just starting out, understanding how Booleans work is essential. Booleans represent the most basic form of data: true and false. In this article, we'll explore the Boolean data type in depth.

What is a Boolean?

In JavaScript, a Boolean is a data type that can only have one of two values: true or false. These values are crucial for making decisions in your code. Think of Booleans as the answers to yes/no questions:

  • Is the user logged in? true or false
  • Is the product in stock? true or false
  • Has the payment been completed? true or false
  • Is LearnYard content awesome? true or true ? ( Yeah here the right answer is only true - I am just kidding, but you get the idea right? )

Example: The Indian Train reservation system

Let’s imagine a scenario most of us are familiar with—booking a train ticket in India. You’re on IRCTC, trying to secure a seat on a train from Delhi to Mumbai. The entire process involves a series of checks that all boil down to Boolean values.

For instance, when you enter your passenger details and select your train, the system needs to verify whether seats are available for your chosen date. This is a simple true or false check.

let seatsAvailable = true; // Assume seats are available

If seatsAvailable is true, you can proceed with the booking. If false, you might need to consider other dates or trains.

Booleans in action

The real power of Booleans lies in how they help us make decisions. In JavaScript, you often use Booleans in conditional statements, like if, else if, and else. Let’s build on our train booking example to see this in action.

Checking Seat Availability

When you search for a train, the system checks whether seats are available:

if (seatsAvailable) {
    console.log("Seats are available! Proceed with your booking.");
} else {
    console.log("Sorry, no seats are available. Please choose a different date or train.");
}

Here, if (seatsAvailable) is a shorthand for if (seatsAvailable === true). JavaScript automatically evaluates the condition based on whether seatsAvailable is true or false.

Boolean Operators

In real-life scenarios, decisions often depend on multiple factors. Boolean operators like && (AND), || (OR), and ! (NOT) allow you to combine multiple conditions.

AND (&&)

Let’s say you want to check not just seat availability but also whether the train is running on time. For this, you’d use the && operator, which ensures both conditions are true.

let trainOnTime = true;

if (seatsAvailable && trainOnTime) {
    console.log("Seats are available and the train is on time. Proceed with your booking.");
} else {
    console.log("Either seats are unavailable or the train is delayed. Please check and try again.");
}

In this scenario, the booking will only proceed if both conditions—seatsAvailable and trainOnTime—are true.

OR (||)

Now, let’s consider a situation where you have more flexibility. Maybe you’re okay with booking a train even if it’s slightly delayed, as long as seats are available. You’d use the || operator here.

if (seatsAvailable || trainOnTime) {
    console.log("You can book your ticket.");
} else {
    console.log("Neither seats are available nor is the train on time. Please check other options.");
}

With the || operator, the booking can proceed if either seatsAvailable or trainOnTime is true. But that is not what you wanted, you are okay with if the train is delayed but would still like to rest on a seat.

NOT (!)

Finally, the ! operator negates a Boolean value. If seatsAvailable is true, !seatsAvailable will be false, and vice versa. This is useful when you want to execute code only when a condition is false.

if (!seatsAvailable) {
    console.log("Sorry, no seats are available.");
} else {
    console.log("Seats are available! Proceed with your booking.");
}

With this change, if seats are not available, you will not book the train but the train could be delayed.

Type Coercion: Truthy and Falsy Values

JavaScript is a flexible language, which means it often coerces (converts) other data types into Booleans in contexts where a Boolean is expected. This concept is known as "truthy" and "falsy" values.

Falsy Values

In JavaScript, the following values are considered falsy, meaning they evaluate to false when used in a Boolean context:

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN (Not-a-Number)

Let’s say you’re checking if a user has entered their phone number during the booking process:

let phoneNumber = ""; // User did not enter a phone number

if (!phoneNumber) {
    console.log("Please enter your phone number.");
} else {
    console.log("Phone number entered. Proceed with booking.");
}

Since an empty string ("") is falsy, !phoneNumber will evaluate to true, prompting the system to ask the user to enter their phone number.

Truthy Values

Conversely, all other values are truthy, meaning they evaluate to true in a Boolean context. For instance:

let discountCode = "DIWALI100"; // User entered a discount code

if (discountCode) {
    console.log("Discount code applied!");
} else {
    console.log("No discount code entered.");
}

Because DIWALI100 is a non-empty string, it’s truthy, and the message "Discount code applied!" will be logged.

Example: Completing the Booking Process

Let’s bring everything together and walk through a simplified booking process on IRCTC, using Booleans to handle the logic.

Step 1: Checking Seat Availability and Train Status

First, you check if seats are available and if the train is on time:

let seatsAvailable = true;
let trainOnTime = false;

if (seatsAvailable && trainOnTime) {
    console.log("Seats are available, and the train is on time. Proceed with booking.");
} else {
    console.log("Please check seat availability or train status again.");
}

Step 2: Confirming User Details

Next, ensure that the user has entered all necessary details, like their phone number and email:

let phoneNumber = "9876543210"; // Not my number!
let email = "user@example.com";

if (phoneNumber && email) {
    console.log("User details confirmed. Proceed with payment.");
} else {
    console.log("Please provide both phone number and email.");
}

Step 3: Applying a Discount Code

Finally, check if the user has entered a valid discount code:

let discountCode = "DIWALI100";
let discountApplied = false;

if (discountCode) {
    discountApplied = true;
    console.log("Discount code applied successfully!");
} else {
    console.log("No discount code entered.");
}

With all these checks in place, the system can confidently proceed to finalize the booking, ensuring that all conditions are met.

Boolean Logic - Let's dive deeper

Booleans don’t just help with simple decisions; they can also be used in more complex logic. Let’s say we introduce an additional factor: whether the user is a member of IRCTC's loyalty program. Members might get priority booking, even if the train is delayed.

let isMember = true;

if ((seatsAvailable && trainOnTime) || isMember) {
    console.log("Booking successful! Thank you for being a loyal customer.");
} else {
    console.log("Booking failed. Please try again later.");
}

In this case too, even if the train isn’t on time, the booking can still succeed because isMember is true.

Boolean Methods

JavaScript provides some useful methods to work with Booleans. Let’s explore a few that might come in handy.

Boolean()

The Boolean() function can convert any value to a Boolean. This is particularly useful when you want to make sure a value is explicitly treated as a Boolean.

let emptyString = "";
let isStringEmpty = Boolean(emptyString); // false

console.log(isStringEmpty); // false

toString()

The toString() method converts a Boolean value to a string, which can be helpful when you need to display the result in a user interface.

let isBookingComplete = true;
let bookingStatus = isBookingComplete.toString();

console.log("Booking complete: " + bookingStatus); // "Booking complete: true"

Common mistakes with Booleans

While Booleans are straightforward, there are some common pitfalls that us developers might encounter.

Misinterpreting Falsy Values

It’s easy to forget that values like 0, "", and null are falsy. This can lead to bugs if you’re not careful.

let seatNumber = 0; // User has not selected a seat

if (!seatNumber) {
    console.log("Please select a seat.");
}

Even though seatNumber is 0, which might be a valid seat number, the condition evaluates to true, leading to an incorrect prompt.

Using == Instead of ===

JavaScript’s == operator performs type coercion, which can sometimes lead to unexpected results. It’s generally safer to use === to avoid these issues.

let isAvailable = "true"; // String instead of Boolean

if (isAvailable == true) {
    console.log("Seats are available.");
} else {
    console.log("No seats available.");
}

// Better to use:
if (isAvailable === true) {
    console.log("Seats are available.");
} else {
    console.log("No seats available.");
}

Booleans may seem simple, but they are the backbone of decision-making in JavaScript. Whether you’re booking a train ticket on IRCTC, validating user input, or applying a discount code, Booleans are there to guide the logic of your code.

Perfect, let's proceed!