Chapter 5

Control Flow

Conditionals and loops

If Statements

Basic conditional execution with if:

age = 18

if (age >= 18) {
    print("You can vote!")
}

If-Else

temperature = 25

if (temperature > 30) {
    print("It's hot!")
} else {
    print("It's comfortable")
}

If-Elif-Else

score = 75

if (score >= 90) {
    print("Grade: A")
} elif (score >= 80) {
    print("Grade: B")
} elif (score >= 70) {
    print("Grade: C")
} elif (score >= 60) {
    print("Grade: D")
} else {
    print("Grade: F")
}

Nested Conditions

hasTicket = true
age = 12

if (hasTicket) {
    if (age >= 13) {
        print("Welcome to the movie!")
    } else {
        print("You need parental guidance")
    }
} else {
    print("Please buy a ticket first")
}

For Loops

Iterate over ranges and collections with for...in:

Range-based Loop

// Count from 0 to 4
for (i in Range(0, 5)) {
    print("Count:", i)
}

// Count from 1 to 10
for (i in Range(1, 11)) {
    print(i)
}

Array Iteration

fruits = ["apple", "banana", "cherry"]

for (fruit in fruits) {
    print("I like", fruit)
}

// With index
for (i in Range(0, len(fruits))) {
    print("Index", i, ":", fruits[i])
}

Nested Loops

// Multiplication table
for (i in Range(1, 4)) {
    for (j in Range(1, 4)) {
        print(i, "x", j, "=", i * j)
    }
    print("")
}

While Loops

Loop while a condition is true:

count = 5

while (count > 0) {
    print("Countdown:", count)
    count = count - 1
}
print("Liftoff!")

Infinite Loop Pattern

// Process until condition met
attempts = 0
success = false

while (not success) {
    attempts = attempts + 1
    print("Attempt", attempts)
    
    if (attempts >= 3) {
        success = true
    }
}

print("Succeeded after", attempts, "attempts")

Truthiness

These values are considered "falsy" in conditions:

  • false
  • nil
  • 0 (integer zero)
  • 0.0 (float zero)
  • "" (empty string)
  • [] (empty array)

Everything else is "truthy":

// These are truthy
if (1) { print("1 is truthy") }
if ("hello") { print("non-empty string is truthy") }
if ([1, 2]) { print("non-empty array is truthy") }

// These are falsy
if (not 0) { print("0 is falsy") }
if (not "") { print("empty string is falsy") }
if (not []) { print("empty array is falsy") }

Logical Short-Circuit

// 'and' short-circuits on first false
x = false and print("won't print")

// 'or' short-circuits on first true
y = true or print("won't print either")

// Useful patterns
name = ""
displayName = name or "Anonymous"
print(displayName)  // "Anonymous"