typestar

if and else in WebAssembly

Branches are typed: a result-carrying if must fill both arms.

(module
  ;; if is typed: (result i32) says both branches leave one value.
  (func (export "abs") (param $n i32) (result i32)
    (if (result i32)
      (i32.lt_s (local.get $n) (i32.const 0))
      (then (i32.sub (i32.const 0) (local.get $n)))
      (else (local.get $n))))

  ;; Without a result type, if is a statement and else may vanish.
  (func (export "cap_at_ten") (param $n i32) (result i32)
    (if (i32.gt_s (local.get $n) (i32.const 10))
      (then (return (i32.const 10))))
    (local.get $n)))

How it works

  1. (if (result i32) ...) promises one value from either branch.
  2. (then ...) and (else ...) each leave that value.
  3. A statement if may skip else; return exits the whole function.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
464
Tokens
108
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 100 seconds.

Type this snippet

Step 1 of 3 in Control flow, step 10 of 28 in Language basics.

← Previous Next →