WebAssembly-JS Interop Deep Dive
Master the boundary between JS and WASM: calling functions, sharing memory, and passing data.
What you'll learn
- Calling WASM functions from JS and vice versa
- Sharing data via linear memory
- Passing strings and complex types across the boundary
- Performance costs of the JS-WASM boundary
Concept
WebAssembly-JS Interop Deep Dive
The JS-WASM boundary is where the two worlds meet. Efficient interop is critical - crossing the boundary has costs.
Function Calls
WASM exports functions that JS calls directly. WASM imports JS functions. Calls are fast for primitives (i32, f64) but require care for complex types.
Sharing Memory
WASM linear memory is an ArrayBuffer accessible from JS. To pass data: JS writes bytes at an offset, calls WASM with offset+length, WASM reads from memory.
String Passing
Strings are not native to WASM. Encode as UTF-8 with TextEncoder, write to memory, pass pointer+length. For return: WASM writes UTF-8 and returns pointer; JS reads with TextDecoder.
Performance Costs
Each boundary crossing has overhead. For small operations, overhead dominates. Batch: call once with an array instead of 1000 times. Keep data on WASM side to minimize crossings.
Example
const memory = new WebAssembly.Memory({initial: 1});
const buf = new Uint8Array(memory.buffer);
function writeString(str, off) { const enc = new TextEncoder().encode(str); for (let i = 0; i < enc.length; i++) buf[off+i] = enc[i]; return {ptr: off, len: enc.length}; }
function readString(ptr, len) { return new TextDecoder().decode(buf.slice(ptr, ptr+len)); }
function writeArray(arr, off) { const v = new Float32Array(memory.buffer, off, arr.length); for (let i = 0; i < arr.length; i++) v[i] = arr[i]; return {ptr: off, len: arr.length}; }
const si = writeString('Hello WASM!', 0);
console.log('Written:', si, 'Read:', readString(si.ptr, si.len));
const ai = writeArray([1.5, 2.5, 3.5], 1024);
console.log('Array at 1024:', ai);
writeString encodes to UTF-8 and writes to WASM memory. readString reads and decodes. writeArray uses typed array view. Batch calls minimize crossings.
Try it
- JSON Formatter
WASM import/export objects are JS objects - format for debugging interop.
Common mistakes
The mistake
Calling WASM in a tight JS loop, paying boundary cost each time.
The fix
Batch work: pass an array to WASM and process in a loop inside WASM.
The mistake
Not using TextEncoder/TextDecoder for strings.
The fix
TextEncoder/TextDecoder are optimized native APIs. Manual conversion is slower and incorrect for multi-byte UTF-8.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.