🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly Exports: Call Wasm from JavaScript

A WebAssembly export is a function or value a module shares with JavaScript. JavaScript calls it through instance.exports after the module starts.

Export add and multiply

This module exports two functions. Each takes two numbers and returns one number.

(module
  (func (export "add") (param i32 i32) (result i32)
    local.get 0
    local.get 1
    i32.add)
  (func (export "multiply") (param i32 i32) (result i32)
    local.get 0
    local.get 1
    i32.mul))

Call the exports

Start the module first. Then call each export by name.

const { instance } = await WebAssembly.instantiate(bytes);
console.log(instance.exports.add(3, 4));
console.log(instance.exports.multiply(3, 4));

List the exports

Object.keys shows every exported name. Here it lists add and multiply.

const { instance } = await WebAssembly.instantiate(bytes);
console.log(Object.keys(instance.exports).join(", "));

Example

(async () => {
  const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAwIAAAcSAgNhZGQAAAhtdWx0aXBseQABChECBwAgACABagsHACAAIAFsCw==";
  const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
  const { instance } = await WebAssembly.instantiate(bytes);
  console.log(instance.exports.add(3, 4));
  console.log(instance.exports.multiply(3, 4));
})();

Key points

  • An export is a name a module shares with JavaScript.
  • Export a function with (export "name") in WAT.
  • JavaScript reads exports from instance.exports.
  • Call an exported function like any JavaScript function.
  • Exported numbers use the same types on both sides.

In this example, the bytes are decoded and started into an instance. Then the code calls the exported add with 3 and 4, which gives 7. Then it calls the exported multiply with 3 and 4, which gives 12.

Note

A name that is not exported stays hidden inside the module.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

How does JavaScript call an exported Wasm function?