Lesson 55 of 55 · javascript
WebAssembly (Wasm) Introduction
Duration: 12 mins
WebAssembly (Wasm) Introduction
WebAssembly is a binary instruction format that runs near native speed in the browser. You compile code written in languages like C, C++, or Rust to a .wasm module and load it from JavaScript.
1️⃣ A tiny Wasm module (C example)
/* hello.c */
#include <stdio.h>
int main(){ printf("Hello from Wasm!\n"); return 0; }
Compile with Emscripten:
emcc hello.c -s WASM=1 -o hello.html
You now have hello.wasm and a small JavaScript loader.
2️⃣ Manual loading in JavaScript
(async () => {
const response = await fetch('add.wasm');
const bytes = await response.arrayBuffer();
const { instance } = await WebAssembly.instantiate(bytes, {
env: { /* imported functions */ }
});
console.log('Result:', instance.exports.add(3,4)); // assume an `add` export
})();
add.wasm could be compiled from:
int add(int a, int b) { return a + b; }
3️⃣ Memory & communication
WebAssembly modules expose a linear memory buffer:
const memory = new WebAssembly.Memory({ initial:1 }); // 64KiB pages
// Pass the memory object in the importObject
const importObject = { env: { memory } };
You can read/write using typed arrays:
const view = new Uint8Array(memory.buffer);
view[0] = 42; // store a byte
4️⃣ When to consider Wasm?
- CPU‑intensive algorithms (image processing, physics, cryptography).
- Re‑using existing native libraries without rewriting them in JS.
- Games or scientific visualisation where performance matters.
Wasm runs in a sandbox – no direct DOM access. Communicate via imports/exports and shared memory.