Overview
Boolean logic is a form of algebra centered around three main logical operators: AND, OR, and NOT. It is the fundamental building block of all digital computers, as it allows the CPU to make decisions based on binary values (true or false, 1 or 0).
Core Concepts
- Boolean Values: Data that can only have one of two possible values:
TrueorFalse. - Basic Logical Operators:
- AND ($\land$): Result is true only if all operands are true.
- OR ($\lor$): Result is true if at least one operand is true.
- **NOT ($
eg$)**: Inverts the value (True $
ightarrow$ False, False $
ightarrow$ True).
- Derived Operators:
- XOR (Exclusive OR): Result is true if exactly one operand is true (but not both).
- NAND (Not AND): The inverse of AND; true unless all inputs are true.
- NOR (Not OR): The inverse of OR; true only if all inputs are false.
- Truth Tables: A mathematical table used to determine the output of a logical expression for all possible combinations of inputs.
Logic Laws
- Identity Law: $A \land ext{True} = A$; $A \lor ext{False} = A$.
- Null Law: $A \land ext{False} = ext{False}$; $A \lor ext{True} = ext{True}$.
- Idempotent Law: $A \land A = A$; $A \lor A = A$.
- De Morgan’s Laws: Critical for simplifying complex logic:
- $
eg(A \land B) =
eg A \lor
eg B$
- $
eg(A \lor B) =
eg A \land
eg B$
Code Examples
// Basic Logic in TypeScript
const isAdult = true;
const hasTicket = false;
// AND: Must have both
const canEnter = isAdult && hasTicket; // false
// OR: Must have at least one
const canEnterWithGuestPass = isAdult || hasTicket; // true
// NOT: Invert the state
const isBanned = false;
const canAccess = !isBanned; // true
// XOR (Implemented using != since there is no native XOR for booleans in TS)
const hasApple = true;
const hasOrange = false;
const hasExactlyOneFruit = hasApple !== hasOrange; // true
Use Cases
- Conditional Statements: The core of
if,while, andforloop conditions. - Circuit Design: Logic gates (AND, OR, NOT gates) in CPU hardware.
- Search Queries: Using “AND”, “OR”, and “NOT” to filter results in databases or search engines.
- Permission Systems: Checking if a user has
(isAdmin OR isEditor) AND isActive.
Gotchas
- Truthiness vs. Booleans: In languages like JavaScript, non-boolean values can be treated as true or false (e.g.,
0is falsy,1is truthy). This is different from strict Boolean logic. - Short-Circuiting: In
A && B, ifAis false,Bis never evaluated. This can lead to bugs ifBwas a function that needed to execute for its side effects.
