Lesson 55 of 55
javascriptWebAssembly (Wasm) Introduction
12 mins
Course progress100%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 55 of 55
javascript12 mins
Keep these ideas in mind as you work through the lesson.
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.
/* hello.c */
#include <stdio.h>
int main(){ printf("Hello from Wasm!
"); return 0; }
Compile with Emscripten:
emcc hello.c -s WASM=1 -o hello.html
You now have hello.wasm and a small JavaScript loader.
(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; }
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
Wasm runs in a sandbox – no direct DOM access. Communicate via imports/exports and shared memory.