Control Flow

Conditionals, loops, and map

If Statements

if temp >= 30 {
  "Hot"
}

The if statement executes a block of code when a condition is true. Add else / else if clauses to handle other cases; conditions are evaluated in order and the first true condition's block executes:

if temp >= 30 {
  "Hot"
} else if temp >= 15 {
  "Warm"
} else {
  "Cold"
}
Run in Browser No model needed

Chain as many else if clauses as needed. If statements can be nested to any depth.

Conditions

Comparison operators (==, !=, <, <=, >, >= — there is no ===/!==):

if temp >= 30 { "Hot" }
if score < 50 { "Failed" }
if status == "active" { "Active" }
if value != null { "Has value" }

Logical operators:

// AND - both must be true
if temp >= 30 && isSunny {
  "Beach day"
}

// OR - at least one must be true
if isAdmin || isOwner {
  "Has access"
}

// NOT - negate a boolean
if !isDisabled {
  "Enabled"
}

// Grouping with parentheses
if (temp >= 30 && isSunny) || isHoliday {
  "Beach day"
}

Truthy/falsy: false, 0, null, "", and missing values are falsy; everything else is truthy.

if count {
  "Count is not zero"
}

Function Calls in Conditions

A function (or method) call can be used directly as an if condition. It is evaluated once, just before the if:

if checkPermission(user: currentUser) {
  "Access granted"
}

Calls are not allowed in else if conditions (they must only run when earlier conditions are false), or in while/do-while conditions (those re-evaluate every iteration, but the call would run only once). In those positions, assign the result to a variable first — the parse error says exactly this.

LLM Conditions

When a branch depends on a judgment rather than a mechanical comparison, make the LLM call explicit. Every model call in a condition costs a round-trip and is non-deterministic, so Kaya requires you to write it where you can see it (and route it — pass model: to send condition checks to a fast, cheap model).

These examples require an admitted model alias or a configured session default. See native model configuration.

Semantic match with is — checks whether a value matches a natural-language description:

if feedback is "asking about pricing" {
  routeToSales()
}

Free-form judgment with generate — ask anything, coerce the answer to a boolean with as (inline in the first condition, or bound to a variable for else if):

if generate(message: "Is {{city}} in the southern hemisphere?", model: "gemini-fast") as boolean {
  "Seasons are flipped"
}

Quoted conditions are a parse error. if "{{temp}} >= 30" used to silently send the rendered text to an LLM to judge true/false — an invisible model call one character away from the free, deterministic if temp >= 30. The parser now rejects it and the error message points at the three explicit forms above.

Loops

Mutation vs. shadowing — read this before writing a loop. let always declares a new variable in the current block. let count = count + 1 inside a loop body creates a block-scoped copy that is thrown away at the end of each iteration — the outer count never advances, and a while count < n loop spins forever. To update an existing variable, assign without let: count = count + 1. The same applies to accumulating strings: content = "{{content}}{{item}}". The compiler flags the broken form as a loop-self-shadow error, so you'll see it before it loops forever.

For Loops

Range loops — range(n) executes the body n times. The bound can be a number literal or any numeric expression (range(count), range(n + 1)); a non-integer or negative bound fails loudly at runtime. Function calls are not allowed inside the bound — assign the result to a variable first.

for i in range(5) {
  "Iteration {{_index}}"
}

Two-argument ranges — range(start, end) iterates the loop variable from start up to (but not including) end. {{_index}} stays 0-based regardless of the start. A backwards range (range(5, 2)) fails loudly; range(n, n) runs zero times. Both bounds accept expressions.

for page in range(3, 8) {
  "Page {{page}} (iteration {{_index}})"   // pages 3..7, _index 0..4
}

let start = 2
let batch = 3
for i in range(start, start + batch) {
  "Item {{i}}"                              // 2, 3, 4
}
Run in Browser No model needed

Array loops — the iterator variable holds the current item. Array literals can be looped directly.

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

for fruit in fruits {
  "I like {{fruit}}"
}

for color in ["red", "green", "blue"] {
  "Color: {{color}}"
}

Special loop variables — _index is the current iteration (0-based); _item is the current item (same value as the iterator variable). In nested loops, each loop has its own _index and _item.

for item in items {
  "Item {{_index}}: {{item}}"
}

While Loops

While loops execute as long as a condition remains true; the condition is checked before each iteration. Note the bare assignment — no let — when advancing the counter:

let count = 0

while count < 5 {
  "Count: {{count}}"
  count = count + 1
}

Conditions can be any boolean expression, including logical operators and negation:

let done = false

while !done {
  let result = processItem()
  if result == "complete" {
    done = true
  }
}

Do-While Loops

The body executes once before the first condition check:

let i = 0

do {
  i = i + 1
  "Iteration {{i}}"
} while i < 10

Forever Loops

forever { } loops until a break (or a return, inside a function). It is equivalent to while true but states the intent directly:

forever {
  let status = checkStatus()
  if status == "complete" {
    break
  }
  "Still working..."
}

Break and Continue

break exits the innermost enclosing loop immediately; continue skips to its next iteration. Both work in for, while, do-while, and forever loops:

for item in items {
  if item == "skip" {
    continue
  }

  if item == "stop" {
    break
  }

  "Process: {{item}}"
}

In nested loops, break and continue only affect the innermost loop containing them.

Guard clauses — use early continues to keep the main loop body unindented:

for user in users {
  if !user.active {
    continue
  }

  if !user.verified {
    continue
  }

  processUser(user: user)
}

Top level: a return at the top level of a program ends the program, with the returned value as the program's output. break and continue outside a loop are compile errors (break-outside-loop / continue-outside-loop).

Return Statement

return exits a function and optionally returns a value. It is valid anywhere inside a function body — including inside loops, where it exits both the loop and the function:

function firstLarge(items: json[]): json {
  for item in items {
    if item.size > 100 {
      return item
    }
  }
  return null
}

At top level, return parses but silently does nothing (see the note above). See Functions for complete details on return statements.

Map Operation

The map operation transforms an array by calling a function once per element:

import process from "processor"

let output = map collection process({})
Run in Browser No model needed

Pass arguments using _item (current item) and _index (current index), plus any outer variables. An output type annotation is optional:

let results: json = map items process(
  input: "{{_item | json}}",
  index: "{{_index}}",
  config: myConfig
)

Annotations go after the collection, before the function call:

let chapters: json = map chapterList #writeIsolated enrichChapter(
  chapter: _item,
  cuisine: cuisine,
  chef: chef
)

See the Annotations Reference for #writeIsolated, #readIsolated, and other map annotations.

Common Patterns

Early Exit

function validateUser(user: json): boolean {
  if !user {
    return false
  }

  if !user.email {
    return false
  }

  return true
}

Use early returns to avoid deep nesting.

let found = null

for item in items {
  if item.id == targetId {
    found = item
    break
  }
}

if found {
  "Found: {{found.name}}"
} else {
  "Not found"
}

Note found = item — using let here would create a block-local shadow and the outer found would stay null.

Batch Processing

let batchSize = 10
let index = 0

while index < items.length {
  let batch = items.slice(start: index, end: index + batchSize)

  for item in batch {
    process(item: item)
  }

  index = index + batchSize
}

Method calls take named arguments, like all Kaya calls — items.slice(index, index + batchSize) is a parse error.

Retry with Exponential Backoff

let maxRetries = 5
let attempt = 0
let delay = 1000

while attempt < maxRetries {
  attempt = attempt + 1

  let result = tryOperation()

  if result.success {
    break
  }

  if attempt < maxRetries {
    sleep(duration: delay)
    delay = delay * 2
  }
}

Best Practices

  1. Assign, don't let, when updating loop state — let inside a loop body shadows and discards
  2. Keep conditions simple: extract complex conditions (and any function calls) into variables
  3. Use early returns and guard clauses to reduce nesting
  4. Use the right loop type: for for known iterations, while for condition-based iteration, do-while to run at least once, forever for explicit run-until-break loops

Next Steps