WebAssembly and JS Interop
Published by Brayan K
WebAssembly (wasm) is a low-level binary instruction format that runs at near-native speed in the browser, letting you compile languages like C, C++, and Rust to code that works alongside JavaScript for performance-critical tasks.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Start with an actual module and a precise numeric contract
WebAssembly is a compilation target with typed operations, not a promise that every task will be faster. Measure the whole workload, including compilation and data crossing the JavaScript boundary. Small DOM-oriented operations may gain nothing. This lesson uses a complete, tiny binary fixture so its behavior can run offline without a compiler or downloaded module.
The bytes below encode one exported function named add with two i32 parameters and an i32 result: local.get 0, local.get 1, i32.add. The first eight bytes are the WebAssembly magic number and binary version. The remaining type, function, export and code sections describe that function. This is a precompiled fixture, not a demonstration of compiling C or Rust.
const bytes = new Uint8Array([0,97,115,109,1,0,0,0,1,7,1,96,2,127,127,1,127,3,2,1,0,7,7,1,3,97,100,100,0,0,10,9,1,7,0,32,0,32,1,106,11]);
console.log(WebAssembly.validate(bytes));
const { module, instance } = await WebAssembly.instantiate(bytes);
console.log(module instanceof WebAssembly.Module);
console.log(instance.exports.add(7, 8));
console.log(WebAssembly.Module.exports(module).map(item => item.name + ":" + item.kind).join(", "));
// ✅ Expected output:
// true
// true
// 15
// add:functionCompilation validates and prepares code. Instantiation supplies imports and creates a runnable instance. Passing bytes to instantiate returns a module/instance pair; passing an already compiled Module returns the Instance itself. A compiled module can be reused to create independent instances.
const bytes = new Uint8Array([0,97,115,109,1,0,0,0,1,7,1,96,2,127,127,1,127,3,2,1,0,7,7,1,3,97,100,100,0,0,10,9,1,7,0,32,0,32,1,106,11]);
const compiled = await WebAssembly.compile(bytes);
const first = await WebAssembly.instantiate(compiled);
const second = await WebAssembly.instantiate(compiled);
console.log(first instanceof WebAssembly.Instance, first !== second);
console.log(first.exports.add(2, 3), second.exports.add(10, 20));
// ✅ Expected output:
// true true
// 5 30For a hosted module, instantiateStreaming can compile from a Response while bytes arrive; the response must use the appropriate application/wasm MIME type. Check HTTP status and deploy headers. This offline fixture does not test hosting, Content Security Policy or streaming delivery.
i32 arithmetic is not unlimited JavaScript number arithmetic
const bytes = new Uint8Array([0,97,115,109,1,0,0,0,1,7,1,96,2,127,127,1,127,3,2,1,0,7,7,1,3,97,100,100,0,0,10,9,1,7,0,32,0,32,1,106,11]);
const { instance } = await WebAssembly.instantiate(bytes);
const add = instance.exports.add;
console.log(add(2147483647, 1));
console.log(add(3.9, 2.1));
console.log(add(4294967296, 1));
try { add(1n, 2n); } catch (error) { console.log(error.name); }
// ✅ Expected output:
// -2147483648
// 5
// 1
// TypeErrorThe i32 result is exposed as a signed JavaScript Number. Inputs use the boundary’s integer conversion, so fractions are truncated and values wrap into 32 bits. Validate inputs in JavaScript when wrapping is not the intended domain behavior. i64 parameters/results use BigInt, while i32 does not accept BigInt here. BigInt & Number Precision owns safe integer representation.
const bytes = new Uint8Array([0,97,115,109,1,0,0,0,1,7,1,96,2,127,127,1,127,3,2,1,0,7,7,1,3,97,100,100,0,0,10,9,1,7,0,32,0,32,1,106,11]);
const { instance } = await WebAssembly.instantiate(bytes);
function boundedAdd(a, b) {
if (![a, b].every(x => Number.isInteger(x) && x >= 0 && x <= 1000000)) {
throw new RangeError("integers from 0 through 1000000 required");
}
return instance.exports.add(a, b);
}
console.log(boundedAdd(999999, 1));
try { boundedAdd(0.5, 1); } catch (error) { console.log(error.name, error.message); }
// ✅ Expected output:
// 1000000
// RangeError integers from 0 through 1000000 requiredSeparate validation failures, import failures and execution traps
const invalid = new Uint8Array([0, 1, 2]);
console.log(WebAssembly.validate(invalid));
try { await WebAssembly.compile(invalid); }
catch (error) { console.log(error.name); }
// ✅ Expected output:
// false
// CompileError// A complete module exporting a parameterless function whose body is unreachable.
const bytes = new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,7,8,1,4,116,114,97,112,0,0,10,5,1,3,0,0,11]);
console.log(WebAssembly.validate(bytes));
const { instance } = await WebAssembly.instantiate(bytes);
try { instance.exports.trap(); } catch (error) { console.log(error.name); }
// ✅ Expected output:
// true
// RuntimeErrorCompileError means the bytes cannot be compiled; LinkError concerns incompatible imports while instantiating; RuntimeError can report a trap from valid running code. Missing or malformed import objects can also produce JavaScript TypeError. Do not catch every failure and report a network error: the failing phase changes what you need to fix. A thrown JavaScript import can propagate its own error.
Memory is bytes, and growing it changes view lifetimes
const memory = new WebAssembly.Memory({ initial: 1, maximum: 2 });
const old = new Uint8Array(memory.buffer);
old[0] = 42;
console.log(old.byteLength);
console.log(memory.grow(1));
console.log(old.byteLength, memory.buffer.byteLength);
console.log(new Uint8Array(memory.buffer)[0]);
try { memory.grow(1); } catch (error) { console.log(error.name); }
// ✅ Expected output:
// 65536
// 1
// 0 131072
// 42
// RangeErrorOne WebAssembly page is 65536 bytes. grow returns the previous page count; exceeding the maximum throws here. Growing non-shared memory detaches the old buffer, even for grow(0), so retain the Memory object and recreate views from its current buffer. Shared memory has different buffer behavior and requires a separate concurrency design; these examples use non-shared memory.
const memory = new WebAssembly.Memory({ initial: 1 });
const view = new DataView(memory.buffer);
view.setUint32(0, 0x01020304, true);
console.log([...new Uint8Array(memory.buffer, 0, 4)].join(", "));
console.log(view.getUint32(0, true), view.getUint32(0, false));
// ✅ Expected output:
// 4, 3, 2, 1
// 16909060 67305985WebAssembly memory operations use little-endian byte order. DataView lets JavaScript state the byte order explicitly. A pointer is a byte offset, not a JavaScript string or object. A pointer/length pair needs bounds checks before making a view. ArrayBuffer holds bytes; typed arrays and DataView provide views over those bytes. This lesson owns the WebAssembly lifetime boundary.
Guided exercise: use the current memory buffer
Fill the literal hints. The byte sequence contains the UTF-8 encoding of Hi; the length counts bytes, not a terminator.
const memory = new WebAssembly.Memory({ initial: 1 });
new Uint8Array(memory.buffer).set([72, 105], 8);
const bytes = new ___(memory.___, 8, 2); // 👉 replace ___ with Uint8Array
// 👉 replace ___ with buffer
console.log(new ___("utf-8", { fatal: true }).decode(bytes)); // 👉 replace ___ with TextDecoder
// ✅ Expected output:
// HiBuild brief: read a bounded UTF-8 string without retaining stale views
Implement readUtf8(memory, pointer, length). Require a WebAssembly.Memory, nonnegative safe-integer offsets and a length of at most 4096 bytes. Reject ranges beyond the current buffer using subtraction so adding two large offsets cannot hide an overflow. Permit an empty range exactly at the end. Decode UTF-8 with fatal errors, and obtain a fresh buffer on every call.
Return a JavaScript string. Do not stop at a zero byte unless the caller’s protocol explicitly requires it: this contract is length-delimited. A decoded string is an independent value, but concurrent writes to shared memory would need synchronization outside this contract.
function readUtf8(memory, pointer, length) {
if (!(memory instanceof WebAssembly.Memory)) throw new TypeError("WebAssembly memory required");
if (!Number.isSafeInteger(pointer) || pointer < 0 ||
!Number.isSafeInteger(length) || length < 0 || length > 4096) {
throw new RangeError("invalid byte range");
}
const buffer = memory.buffer;
if (pointer > buffer.byteLength || length > buffer.byteLength - pointer) {
throw new RangeError("byte range exceeds memory");
}
const bytes = new Uint8Array(buffer, pointer, length);
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
}
const memory = new WebAssembly.Memory({ initial: 1, maximum: 2 });
const encoded = new TextEncoder().encode("café");
new Uint8Array(memory.buffer).set(encoded, 12);
console.log(encoded.length, readUtf8(memory, 12, encoded.length));
memory.grow(1);
console.log(readUtf8(memory, 12, encoded.length));
console.log(JSON.stringify(readUtf8(memory, memory.buffer.byteLength, 0)));
try { readUtf8(memory, memory.buffer.byteLength, 1); }
catch (error) { console.log(error.name, error.message); }
new Uint8Array(memory.buffer)[0] = 255;
try { readUtf8(memory, 0, 1); } catch (error) { console.log(error.name); }
// ✅ Expected output:
// 5 café
// café
// ""
// RangeError byte range exceeds memory
// TypeErrorTest zero length, the exact end, one byte beyond, fractional and unsafe offsets, malformed UTF-8, a multibyte character, a maximum-length range and growth between calls. This reader does not allocate or free a module’s memory. A real library must document ownership, allocator lifetime and whether another call may invalidate a pointer.
Large CPU work may still block the page when called synchronously. Web Workers (Background Threads) owns moving work off the main thread. Compiling to WebAssembly alone does not create a worker.
Practice quiz
What does this complete program print? const bytes = new Uint8Array([0,97,115,109,1,0,0,0,1,7,1,96,2,127,127,1,127,3,2,1,0,7,7,1,3,97,100,100,0,0,10,9,1,7,0,32,0,32,1,106,11]); const {instance}=await WebAssembly.instantiate(bytes);console.log(instance.exports.add(2147483647,1));
- -2147483648
- 2147483648
- 0
- RangeError
Answer: -2147483648. The i32 addition wraps and is exposed as a signed number.
What does this complete program print? const bytes = new Uint8Array([0,97,115,109,1,0,0,0,1,7,1,96,2,127,127,1,127,3,2,1,0,7,7,1,3,97,100,100,0,0,10,9,1,7,0,32,0,32,1,106,11]); const m=await WebAssembly.compile(bytes);const i=await WebAssembly.instantiate(m);console.log(i instanceof WebAssembly.Instance);
- false
- true
- undefined
- TypeError
Answer: true. The Module overload returns the instance directly.
What does this complete program print? const m=new WebAssembly.Memory({initial:1,maximum:2});const old=m.buffer;m.grow(1);console.log(old.byteLength);
- 65536
- 131072
- 0
- 1
Answer: 0. The old non-shared buffer is detached after growth.
What does this complete program print? console.log(new TextEncoder().encode("é").length);
- 0
- 1
- 4
- 2
Answer: 2. UTF-8 uses two bytes here; JavaScript string length is a different measure.
Which measurement determines whether WebAssembly helps a page?
- The complete real workload including boundary and setup costs
- The language name alone
- Only the source file size
- The presence of a wasm suffix
Answer: The complete real workload including boundary and setup costs. Performance depends on the actual workload and integration.
A valid module reaches an unreachable instruction. Which category describes the trap?
- CompileError
- RuntimeError
- A guaranteed HTTP 404
- SyntaxError in the page
Answer: RuntimeError. Validation can succeed while execution later traps.
What should a pointer/length reader check?
- Only that pointer is truthy
- Only the last character
- Integer bounds against the current buffer before constructing a view
- Nothing because WebAssembly validates every JavaScript view
Answer: Integer bounds against the current buffer before constructing a view. Module validation does not supply the caller’s application-level boundary contract.
What is outside this offline lesson’s checks?
- Real binary compilation
- Calling a real export
- Reading actual linear memory
- Production MIME, CSP and streaming delivery
Answer: Production MIME, CSP and streaming delivery. The fixture avoids a hosted network and does not certify its configuration.
Continue this course
- Previous: Service Workers & PWAs
- Next: Advanced State Management — Stores, observers, immutable updates and reducers without a framework
- Quick reference: JavaScript cheat sheet