🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly.instantiate

WebAssembly.instantiate is the function that turns a module into a running instance. It takes the module and an import object that supplies what the module needs.

A module that imports a function

This module imports double from env. Its quad function calls double twice.

(module
  (import "env" "double" (func $double (param i32) (result i32)))
  (func (export "quad") (param i32) (result i32)
    local.get 0
    call $double
    call $double))

Supply the matching import object

The import object has an env group. That group holds a double function.

const importObject = {
  env: {
    double: (x) => x * 2,
  },
};
const { instance } = await WebAssembly.instantiate(bytes, importObject);
console.log(instance.exports.quad(3));

A missing import fails

Leave double out of the import object. Then instantiation fails with an error.

const importObject = { env: {} };
const { instance } = await WebAssembly.instantiate(bytes, importObject);

Example

(async () => {
  const B64 = "AGFzbQEAAAABBgFgAX8BfwIOAQNlbnYGZG91YmxlAAADAgEABwgBBHF1YWQAAQoKAQgAIAAQABAACw==";
  const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
  const { instance } = await WebAssembly.instantiate(bytes, {
    env: { double: (x) => x * 2 },
  });
  console.log(instance.exports.quad(3));
  console.log(instance.exports.quad(5));
})();

Key points

  • Instantiate means to start a module into a running instance.
  • The first argument is the module or its bytes.
  • The second argument is the import object.
  • The import object groups imports by module name.
  • A missing import stops instantiation with an error.

In this example, the bytes are decoded and passed to instantiate with an import object. The import object supplies double, which doubles its input. Then quad(3) doubles 3 to 6 and doubles 6 to 12. And quad(5) doubles 5 to 10 and doubles 10 to 20.

Note

Check the import object first when loading fails.

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

What is the second argument to WebAssembly.instantiate?