Functions, Imports and Exports
7.1 Functions and Types
(module
(type $unary (func (param f64) (result f64)))
(func $double (type $unary) (f64.mul (local.get 0) (f64.const 2)))
(func $divmod (param $a i32) (param $b i32) (result i32 i32) ;; multi-value results
(i32.div_u (local.get $a) (local.get $b))
(i32.rem_u (local.get $a) (local.get $b)))
(export "double" (func $double))
(export "divmod" (func $divmod)))const [q, r] = instance.exports.divmod(17, 5); // multi-value returns an array in JS → [3, 2]7.2 Importing Host Functions
An import has a two-level name (module name + field name). Imports can be functions, memories, tables, globals, or tags.
(module
(import "console" "log" (func $log (param i32)))
(import "math" "random" (func $random (result f64)))
(func (export "run")
(call $log (i32.const 42))
(call $log (i32.trunc_f64_s (f64.mul (call $random) (f64.const 100))))))const imports = {
console: { log: (x) => console.log("from wasm:", x) },
math: { random: Math.random },
};
const { instance } = await WebAssembly.instantiateStreaming(fetch("imports.wasm"), imports);
instance.exports.run();7.3 Exports
Exports expose functions, memories, tables, globals, and tags by name. They're accessible in JS via instance.exports.
The start function runs automatically at instantiation (avoid heavy work there, and note that exports aren't available to JS during it).