break

The break statement exits a loop immediately, skipping any remaining iterations.

Syntax

break;

Usage

Use break inside while, for, or for-in loops to exit early when a condition is met.

Example: Exit on condition

class App {
    let found = false;
    let i = 0;
    
    @unsafe while (i < 100) {
        if (i == 42) {
            found = true;
            break;     // exit loop immediately
        }
        i = i + 1;
    }
    
    print("Found at:", i);  // Found at: 42
}

Example: for-in with break

class App {
    let items = ["apple", "banana", "cherry", "date"];
    
    for (item in items) {
        if (item == "cherry") {
            print("Found cherry!");
            break;     // stop searching
        }
        print("Checked:", item);
    }
    // Output: Checked: apple
    //         Checked: banana
    //         Found cherry!
}

Nested loops

break only exits the innermost loop it is placed in:

class App {
    @unsafe for (let i = 0; i < 3; i = i + 1) {
        for (let j = 0; j < 3; j = j + 1) {
            if (j == 1) {
                break;     // exits inner loop only
            }
            print(i, j);
        }
    }
    // Output: 0 0
    //         1 0
    //         2 0
}

See also