PROGRAMMING-CONCEPTS

Booleans: Definition, Purpose, and Examples

A Boolean is a data type that represents one of two values: true or false. These values help programs make decisions, react to conditions, and branch into different execution paths. Boolean logic powers everything from login checks to UI visibility to data filtering.


What a Boolean Represents

A Boolean expresses a simple truth value:

  • True: a condition is satisfied
  • False: a condition is not satisfied

This binary choice is the basis of all conditional logic.


Booleans Across Languages

Every major language includes a Boolean type, even though the syntax differs slightly.

Python:

is_logged_in = True
has_items = False

Here, Python capitalizes True and False because they are built-in constants.

JavaScript / TypeScript:

let isLoggedIn = true;
let hasItems = false;

JavaScript uses lowercase keywords for Boolean literals.

Swift:

var isLoggedIn = true
var hasItems = false

Swift follows JavaScript’s lowercase pattern but enforces type safety.


Where Booleans Come From

Most Booleans don’t start as raw values. They are created when expressions are evaluated.

Comparison Expressions

These expressions check a condition and produce a Boolean automatically.

Python:

age > 18

This returns true only when the age is greater than 18.

JavaScript:

name !== "Admin"

If the string does not match "Admin," the expression becomes true.

Swift:

let passed = score >= 50

Swift stores the result of a comparison directly into a Boolean variable.

These comparisons let your program check numeric ranges, user input, or state changes.


How Booleans Control Flow

Conditions in code rely entirely on Boolean values.

Python:

if is_logged_in:
    print("Welcome back!")

If the Boolean is true, the corresponding block runs.

JavaScript:

if (hasItems) {
  checkout();
}

Booleans allow functions to run selectively based on user state.

Swift:

if isReady {
    launch()
}

This mechanism controls which parts of the program execute.


Boolean Operators

Combining multiple conditions lets you express more complex logic.

Python:

eligible = age >= 18 and country == "US"

Both sides must be true for the entire expression to become true.

JavaScript:

const canAccess = isLoggedIn && isVerified;

Logical AND (&&) ensures both requirements are satisfied.

Swift:

let canVote = age >= 18 && isCitizen

This is especially useful when validating multiple criteria.


Truthy and Falsy Values

Some languages treat non-Boolean values as true or false when used in conditions.

JavaScript’s Truthiness Model

if ("hello") console.log("truthy");

Any non-empty string is considered truthy, so the condition executes.

if (0) console.log("runs");

Zero is falsy, so this block does not run.

JavaScript’s flexibility is powerful but requires careful attention to avoid unintended behavior.

Python’s Equivalent Behavior

Python also treats some values as false in conditions:

if "hello":
    print("truthy")

Like JavaScript, non-empty strings are truthy.

if 0:
    print("won't run")

Zero evaluates as false, so the condition fails.

Swift Takes a Stricter Approach

Swift requires an actual Boolean:

if 1 { }  // not allowed in Swift

Swift’s stricter rules prevent ambiguous truthiness.


Real-World Example: Form Validation

Here, a Boolean decides whether the user’s input is valid.

JavaScript:

function isValidEmail(email) {
  return email.includes("@");
}

The .includes() method produces a Boolean, letting the condition be checked easily.

Python:

def is_valid_email(email):
    return "@" in email

The in operator evaluates to true only when the substring exists.

These patterns help prevent invalid submissions.


Real-World Example: Filtering Lists

Filtering collections relies on Boolean expressions to determine which items stay.

Python:

numbers = [1, 2, 3, 4, 5]
evens = [n for n in numbers if n % 2 == 0]

Each element is tested; only those with an even remainder return true.

JavaScript:

const evens = numbers.filter(n => n % 2 === 0);

The callback returns a Boolean that decides whether the element passes through.

This makes Booleans essential for data processing.


Booleans in React

React uses Booleans extensively to control UI rendering.

function Dashboard() {
  const [open, setOpen] = useState(false);

  return (
    <><button onClick={() => setOpen(!open)}>Toggle</button>
      {open && <Menu />}
    </>
  );
}

The menu component appears only when open is true.

React relies on this pattern for conditional display logic.


Booleans in SwiftUI

SwiftUI mirrors React’s approach:

if showDetails {
    Text("Details appear here.")
}

The view shows only when the Boolean is true.

This pattern keeps UI state predictable and easy to follow.


Booleans in SQL

Even though some SQL dialects lack a native Boolean type, SQL queries still evaluate conditions to true or false internally.

SELECT * FROM users WHERE age > 18;

Rows are returned only when the condition evaluates as true for that row.

This is Boolean logic applied to data selection.


Common Mistakes When Working With Booleans

Confusing Assignment and Comparison

JavaScript:

if (active = true) { }

This assigns rather than checks — the condition always becomes true.

Using Booleans to store too many states

If you track more than two states, a Boolean becomes limiting; a string or enum is safer.

Misunderstanding truthiness across languages

A value that is truthy in JavaScript isn’t necessarily valid in Swift.

Returning strings instead of Booleans

return "true"; // not a Boolean

This can break conditional checks unexpectedly.


Summary

A Boolean represents true or false and sits at the heart of decision-making in programming. It controls flow, filters data, determines UI visibility, validates input, and ties multiple conditions together through logical operators. Across Python, JavaScript, TypeScript, Swift, React, and SQL, Booleans make software interactive and intelligent.

Learn to Code for Free
Start learning now
button icon
To advance beyond this tutorial and learn to code by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

Reach your coding goals faster