A second language for the web
WebAssembly (wasm) is a compact binary instruction format that browsers run at near-native speed. C, C++, Rust and Go compile to it — Figma, Photoshop on the web and the PostgreSQL in your SQL lessons all run as wasm. It's a stack machine with typed instructions, just like the assembly you've seen.
// A complete WebAssembly module (41 bytes) exporting add(a, b). const ADD_WASM = new Uint8Array([ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, // magic "\0asm", version 1 0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, // type section: (i32, i32) -> i32 0x03, 0x02, 0x01, 0x00, // function section: one function of type 0 0x07, 0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00, // export section: "add" = function 0 0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b, // code: local.get 0, local.get 1, i32.add, end ]);
Compile, instantiate, call
function instantiate(bytes) {
const module = new WebAssembly.Module(bytes); // compile (validates every byte)
return new WebAssembly.Instance(module).exports; // link and create
}
function describe(bytes) {
const module = new WebAssembly.Module(bytes);
return {
exports: WebAssembly.Module.exports(module).map((e) => `${e.kind} ${e.name}`),
imports: WebAssembly.Module.imports(module).length,
};
}Real apps use await WebAssembly.instantiateStreaming(fetch("app.wasm")); the synchronous API is fine for tiny modules.