WebAssembly JavaScript API
The WebAssembly JavaScript API is the set of objects and functions that load and control modules. It covers compiling, starting, checking, memory, tables, and globals.
Check bytes with validate
These eight bytes are the smallest valid module. Validate returns true for them.
const bytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]);
console.log(WebAssembly.validate(bytes));Compile, then start
Compile the bytes into a module. Then start the module into an instance.
const bytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]);
const module = await WebAssembly.compile(bytes);
const instance = await WebAssembly.instantiate(module, {});
console.log(instance instanceof WebAssembly.Instance);Create the helper objects
Memory holds bytes. Table holds functions. Global holds one shared value.
const memory = new WebAssembly.Memory({ initial: 1 });
const table = new WebAssembly.Table({ initial: 1, element: "anyfunc" });
const counter = new WebAssembly.Global({ value: "i32", mutable: true }, 0);
console.log(memory.buffer.byteLength);Example
(async () => {
const bytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]);
console.log(WebAssembly.validate(bytes));
const module = await WebAssembly.compile(bytes);
const instance = await WebAssembly.instantiate(module, {});
console.log(instance instanceof WebAssembly.Instance);
})();Key points
- WebAssembly.compile turns bytes into a module.
- WebAssembly.instantiate turns a module into a running instance.
- WebAssembly.validate checks bytes and returns true or false.
- A Module holds compiled code before it runs.
- An Instance holds the running module and its exports.
In this example, validate checks the eight header bytes and returns true. Then compile turns the bytes into a module. Then instantiate starts the module, and the check confirms the result is an Instance.
Note
Memory, Table, and Global are objects the API can also create.
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 does WebAssembly.validate return for a valid module?