WebAssembly Overview
WebAssembly (Wasm) is a binary instruction format that runs in the browser at near-native speed. It's not a programming language itself — you write code in languages like C, C++, Rust, or Go, and compile it to Wasm. JavaScript can then call into this compiled code.
// Loading a WebAssembly module
async function loadWasm() {
const response = await fetch("module.wasm");
const bytes = await response.arrayBuffer();
const { instance } = await WebAssembly.instantiate(bytes);
console.log(instance.exports.add(2, 3)); // 5
}
loadWasm();
Why WebAssembly?
Wasm is useful for performance-critical tasks like game engines, video editing, cryptography, and scientific simulations. It runs much faster than JavaScript for CPU-intensive work, while still being able to interact with JavaScript and the DOM.
// JavaScript vs Wasm for heavy computation
// JS: ~100ms for large matrix multiply
// Wasm: ~5ms for the same operation
Using Wasm from JavaScript
The WebAssembly JavaScript API lets you load, compile, and instantiate Wasm modules. You interact with exported functions just like regular JavaScript functions.
const importObject = {
env: {
memory: new WebAssembly.Memory({ initial: 256 }),
log: (value) => console.log("Wasm says:", value),
},
};
WebAssembly.instantiateStreaming(fetch("module.wasm"), importObject)
.then(({ instance }) => {
instance.exports.processData();
});
Try it Yourself →
Wasm and JavaScript Together
Wasm doesn't replace JavaScript — it complements it. Use JavaScript for DOM manipulation, UI logic, and glue code. Use Wasm for the heavy computational parts.
// Typical architecture
// 1. JavaScript handles UI and event handling
// 2. Wasm handles heavy computation
// 3. They share data via SharedArrayBuffer or pass messages
async function runComputation(data) {
const wasm = await loadModule();
const ptr = wasm.exports.malloc(data.length * 4);
// Copy data to Wasm memory, process, get results
const result = wasm.exports.process(ptr, data.length);
wasm.exports.free(ptr);
return result;
}
Summary
WebAssembly brings near-native performance to the browser. Use it alongside JavaScript for compute-heavy tasks. It's compiled from other languages, not written directly.