What is WebAssembly?
WebAssembly (Wasm) is a low‑level binary format that runs natively in modern browsers. It provides a compilation target for languages like C, C++, Rust, and many others, enabling near‑native performance inside the sandboxed web environment.
Why Use WebAssembly?
- Performance: Execute compute‑heavy code at speeds comparable to native binaries.
- Portability: Write once, run everywhere that supports the WebAssembly runtime.
- Interoperability: Seamlessly call JavaScript and be called from JavaScript.
- Security: Runs in a sandbox with the same-origin and same-site policies as JavaScript.
Your First “Hello, WebAssembly!”
Below is a minimal example using the wat2wasm text format to compile a simple function that returns 42.
(module
(func $answer (result i32)
i32.const 42)
(export "answer" (func $answer)))
Compile with wat2wasm hello.wat -o hello.wasm and load it in the browser:
const importObject = {};
fetch('hello.wasm')
.then(r => r.arrayBuffer())
.then(bytes => WebAssembly.instantiate(bytes, importObject))
.then(results => {
console.log('Answer from WASM:', results.instance.exports.answer());
});
Tooling & Ecosystem
Popular tools and runtimes include:
- Rust + wasm-pack: Idiomatic Rust tooling for building packages.
- Emscripten: Compile C/C++ code to WebAssembly with a familiar toolchain.
- AssemblyScript: TypeScript‑like syntax that compiles to Wasm.
- WASI: System interface for running Wasm outside the browser.
The Future of WebAssembly
Upcoming proposals such as Garbage Collection, Threads, and SIMD are expanding Wasm’s capability to handle more complex workloads, from gaming to AI inference.