Booleans

What are booleans?

Booleans are values that are either true or false. They’re the simplest data type but incredibly important for making decisions and controlling program flow.

Benefits of using booleans?

  • Make yes/no decisions in your code
  • Control whether code runs or not
  • Track states (is player alive? is button pressed?)
  • Combine conditions with logic operators
  • Essential for all conditional logic
const isPlayerAlive = true;
const isGameOver = false;
const hasCollectible = true;

// Comparison operators
const playerHealth = 50;
const maxHealth = 100;

console.log(playerHealth > 0); // true
console.log(playerHealth === maxHealth); // false
console.log(playerHealth < maxHealth); // true
console.log(playerHealth <= 50); // true

// Logical operators
const hasShield = true;
const canMove = true;

console.log(hasShield && canMove); // true
console.log(hasShield || isGameOver); // true
console.log(!isGameOver); // true

// Using in code
if (isPlayerAlive && playerHealth > 0) {
    console.log("Player is still in the game!");
}

What does this code do?

  • Combines multiple conditions with && and ! operators
  • Stores boolean results in variables for reuse
  • Uses canShoot to check multiple requirements before allowing action
  • Loops through enemies and checks alive boolean for each
  • Shows practical game logic: only alive enemies are processed
  • Demonstrates how booleans control program flow

Try It Yourself

%%js // CODE_RUNNER: booleans const isAlive = true; const hasHealth = 50 > 0; console.log(isAlive && hasHealth); console.log(isAlive || !hasHealth); if (isAlive) { console.log(“Player is alive”); }