TExcelTAD
Home › WebAssembly › Loops

Loops

A loop looks like a block, with one crucial difference: branching to a loop jumps back to its start, not its end. A loop does not repeat by itself. If execution reaches its end, it simply falls through. You repeat by branching back with br/br_if.

Construct br to its label jumps to…
block the end (exit)
loop the start (continue)
if the end

Counting up

The basic pattern is: do the work, update the counter, and br_if back to the loop while the condition holds.

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (func (export "main")
    (local $i i32)
    (loop $again
      (call $log (local.get $i))
      (local.set $i (i32.add (local.get $i) (i32.const 1)))
      (br_if $again (i32.lt_s (local.get $i) (i32.const 5))))))
0
1
2
3
4

This is a do-while loop: the body always runs at least once, and the test is at the bottom.

While loops: block + loop

To test the condition before each iteration (a while or for loop), wrap the loop in a block. Exit by branching to the block, continue by branching to the loop:

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  ;; sum of 1..n, for n >= 0
  (func $sum_to (param $n i32) (result i32)
    (local $i i32) (local $total i32)
    (local.set $i (i32.const 1))
    (block $exit
      (loop $next
        (br_if $exit (i32.gt_s (local.get $i) (local.get $n)))      ;; while i <= n
        (local.set $total (i32.add (local.get $total) (local.get $i)))
        (local.set $i (i32.add (local.get $i) (i32.const 1)))
        (br $next)))
    (local.get $total))
  (func (export "main")
    (call $log (call $sum_to (i32.const 10)))
    (call $log (call $sum_to (i32.const 100)))
    (call $log (call $sum_to (i32.const 0)))))
55
5050
0

For n = 0 the condition fails immediately and the body never runs. This block/loop pair is what every compiler emits for a while loop, so you'll see it constantly in real Wasm.

Loops with break and continue

With labels for both the block and the loop you can express break (br $exit) and continue (br $loop). This example sums the odd numbers below 20 and stops early once the sum exceeds 50:

wat · try it yourself
(module
  (import "console" "log" (func $log2 (param i32 i32)))
  (func (export "main")
    (local $i i32) (local $sum i32)
    (block $break
      (loop $continue
        (local.set $i (i32.add (local.get $i) (i32.const 1)))
        (br_if $break (i32.ge_s (local.get $i) (i32.const 20)))       ;; for i in 1..19
        (br_if $continue (i32.eqz (i32.rem_u (local.get $i) (i32.const 2))))   ;; skip evens
        (local.set $sum (i32.add (local.get $sum) (local.get $i)))
        (br_if $break (i32.gt_s (local.get $sum) (i32.const 50)))   ;; early exit
        (br $continue)))
    (call $log2 (local.get $i) (local.get $sum))))
15 64

It stopped at i = 15 with 1 + 3 + 5 + … + 15 = 64.

Nested loops

Each loop needs its own counter and labels. Here is a small multiplication table printed with console.log:

wat · try it yourself
(module
  (import "console" "log" (func $log3 (param i32 i32 i32)))
  (func (export "main")
    (local $row i32) (local $col i32)
    (local.set $row (i32.const 1))
    (loop $rows
      (local.set $col (i32.const 1))
      (loop $cols
        (call $log3 (local.get $row) (local.get $col)
                    (i32.mul (local.get $row) (local.get $col)))
        (local.set $col (i32.add (local.get $col) (i32.const 1)))
        (br_if $cols (i32.le_s (local.get $col) (i32.const 3))))
      (local.set $row (i32.add (local.get $row) (i32.const 1)))
      (br_if $rows (i32.le_s (local.get $row) (i32.const 2))))))
1 1 1
1 2 2
1 3 3
2 1 2
2 2 4
2 3 6

Loops with a value

Loops can have a result type too, but remember that branching to a loop goes to its start, which takes no operands (in the classic form). The result is produced when the loop falls off its end. A neat example is Euclid's greatest common divisor:

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (func $gcd (param $a i32) (param $b i32) (result i32)
    (local $t i32)
    (loop $step (result i32)
      (if (result i32) (i32.eqz (local.get $b))
        (then (local.get $a))
        (else
          (local.set $t (i32.rem_u (local.get $a) (local.get $b)))
          (local.set $a (local.get $b))
          (local.set $b (local.get $t))
          (br $step)))))
  (func (export "main")
    (call $log (call $gcd (i32.const 48) (i32.const 18)))
    (call $log (call $gcd (i32.const 17) (i32.const 5)))
    (call $log (call $gcd (i32.const 100) (i32.const 75)))))
6
1
25

The else branch never produces a value: it ends with br $step, after which the stack is polymorphic, so the validator accepts it.

Infinite loops

If the condition never becomes false, the loop runs forever and the page's worker hangs. The playground stops runs that take too long. In a real page, long-running Wasm should run in a Web Worker so it can't freeze the UI.

Tip: When a loop misbehaves, log the counter at the top of the body. Off-by-one errors usually come from using lt vs le, or from updating the counter before vs after the test.

Test yourself

Where does br $l jump when $l labels a loop?

  1. To the end of the loop
  2. To the start of the loop
  3. To the end of the function
  4. It is not allowed

What happens when execution reaches the end of a loop without branching?

  1. It repeats automatically
  2. It falls through and continues after the loop
  3. It traps
  4. It returns from the function

How is a while loop (test before the body) usually written?

  1. A loop alone with br_if at the bottom
  2. A block containing a loop: br_if to the block exits, br to the loop repeats
  3. Two nested loops
  4. With br_table