2 min read

Booleans

A Boolean is a data type that has one of two possible values (usually denoted as true and false). It is named after George Boole, who defined an algebraic system of logic in the mid-19th century.

1. The Core Concept

Booleans are the basis of all decision-making in computer programming. They represent the answer to a Yes/No question.

  • Values: true / false (or 1 / 0 in some languages like C).
  • Memory: Theoretically requires only 1 bit, but usually stored as a byte (8 bits) for addressing reasons.

2. Logical Operators

Booleans are often combined using logical operators to form complex conditions.

AND (&& or and)

Returns true if both operands are true.

  • true && true -> true
  • true && false -> false

OR (|| or or)

Returns true if at least one operand is true.

  • true || false -> true
  • false || false -> false

NOT (! or not)

Inverts the value.

  • !true -> false
  • !false -> true

3. Comparison Operators

Comparison operators return boolean values.

  • == (Equal to)
  • != (Not equal to)
  • > (Greater than)
  • < (Less than)
  • >= (Greater than or equal to)
  • <= (Less than or equal to)
let age = 18;
let isAdult = age >= 18; // true

4. Truthy and Falsy

In dynamically typed languages (like JavaScript and Python), non-boolean values can be evaluated in a boolean context (like an if statement).

JavaScript

  • Falsy: false, 0, "" (empty string), null, undefined, NaN.
  • Truthy: Everything else (including "0", [], {}).

Python

  • Falsy: False, 0, "", [], {}, None.
  • Truthy: Everything else.

5. Short-Circuit Evaluation

Logical operators are evaluated from left to right. If the result is determined early, the rest of the expression is ignored.

  • AND (&&): If the first operand is false, the result is false. The second operand is not evaluated.
  • OR (||): If the first operand is true, the result is true. The second operand is not evaluated.

This is often used for safety checks or default values.

6. De Morgan's Laws

De Morgan's Laws provide a way to simplify complex boolean expressions involving the NOT operator. They describe how to distribute a negation across AND and OR operations.

  1. NOT (A AND B) = (NOT A) OR (NOT B)

    • !(A && B) is equivalent to !A || !B
    • Meaning: "Not both" is the same as "Not one or not the other".
  2. NOT (A OR B) = (NOT A) AND (NOT B)

    • !(A || B) is equivalent to !A && !B
    • Meaning: "Not either" is the same as "Neither one nor the other".

programming/common-syntax programming/control-flow programming/bit-manipulation