Skip to content
Tutorials Center
My learning

Topics

Lesson 125 of 156 ยท Under the Hood

WebAssembly Basics

Learn what WebAssembly is, how to load and instantiate a .wasm module from JavaScript, call exports, provide imports, and share linear memory with typed arrays.

JavaScript is flexible, but it was not designed for heavy number crunching such as video codecs, image filters, physics engines, cryptography or a complete database. WebAssembly (often written Wasm) is the answer: a compact binary instruction format that browsers run at near-native speed, in the same sandbox as JavaScript. You rarely write it by hand. Instead you compile programs written in Rust, C, C++, Go, Zig or AssemblyScript into a .wasm file and load that file from your page.

This lesson is about the JavaScript side of that story: how to load a module, call the functions it exports, give it functions to call back, and share memory with it. To keep everything runnable inside the editor, the modules here are tiny and are embedded as arrays of bytes, so you can see exactly what a .wasm file is made of.

What WebAssembly is (and is not)

  • A compilation target, not a language you write. A tool turns Rust or C++ into .wasm; your JavaScript loads it. The text form, WAT, exists for humans to read, but real projects ship the binary.
  • Fast and predictable. The code is already compiled and typed, so the browser can turn it into machine code quickly, without the guessing that JavaScript engines do.
  • Safe. A module runs in a sandbox. It cannot touch the DOM, the network or files; it can only use the functions you explicitly hand it.
  • A partner to JavaScript, not a replacement. JavaScript still handles the page, events and the DOM. Wasm takes the hot loops. Many sites use it without anyone noticing: image editors, CAD tools, games, PDF viewers, SQLite in the browser and video conferencing.
  • Not automatically faster. Calling between JavaScript and Wasm has a cost, and for ordinary DOM-heavy code JavaScript is just as good. Measure before you rewrite anything. See JavaScript Performance.
flowchart LR
  A["Source code<br/>(Rust, C, C++, Go ...)"] -->|"compiler"| B["module.wasm<br/>(binary)"]
  B -->|"fetch()"| C["bytes in JavaScript"]
  C -->|"WebAssembly.instantiate()"| D["Instance"]
  D --> E["exports<br/>(functions, memory)"]
  F["imports object<br/>(JS functions you provide)"] --> D

A compiler produces the .wasm file; JavaScript fetches it, instantiates it with imports, and uses its exports.

Modules and instances

Two words matter:

  • A Module is the compiled, stateless code. It can be cached or even sent to a worker.
  • An Instance is a module plus its own memory and state, with its exports (what you can call) wired up and its imports (what it needs from you) provided.

WebAssembly.instantiate(bytes, imports) does both steps and resolves with { module, instance }. WebAssembly.validate(bytes) checks quickly whether bytes form a valid module without compiling them.

Your first module

The smallest useful module exports one function that adds two 32-bit integers. In the text format it would be written like this (read-only; the editor cannot compile WAT):

TEXT
(module
  (func (export "add") (param i32 i32) (result i32)
    local.get 0
    local.get 1
    i32.add))

Compiled, it is just 41 bytes. Every module starts with the magic number 00 61 73 6d (the characters \0asm) and a version, followed by numbered sections: types, functions, exports, code and so on. Each section has an id, a byte size and its contents. The comments below label them:

JS Load a module from bytes and call it

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What the output teaches you:

  • Exports are ordinary functions. instance.exports.add is a JavaScript function you call with normal arguments.
  • Types are strict inside Wasm. Wasm has only four number types: i32, i64, f32 and f64. When you pass a JavaScript number to an i32 parameter it is converted (1.9 becomes 1), and the result wraps around on overflow like a real 32-bit integer. An i64 value is exchanged with JavaScript as a BigInt (see BigInt and Symbol).
  • Bad input fails loudly. A file that is not valid Wasm rejects with a WebAssembly.CompileError.

Loading a .wasm file in a real page

In an application the bytes live in a file served by your web server. The best way to load it is WebAssembly.instantiateStreaming(), which compiles the module while it downloads (using the streams machinery):

JavaScript
// Read-only: needs a real server that sends the file with Content-Type: application/wasm
const imports = { env: { log: (n) => console.log("from wasm:", n) } };

const { instance } = await WebAssembly.instantiateStreaming(
  fetch("/wasm/math.wasm"),
  imports,
);

console.log(instance.exports.add(20, 22)); // 42

Make sure your server sends Content-Type: application/wasm; otherwise instantiateStreaming rejects. If you can't control it, fall back to fetch(...).then((r) => r.arrayBuffer()) followed by WebAssembly.instantiate(buffer, imports). Fetching follows the usual rules for fetch, including CORS.

Imports: letting Wasm call JavaScript

A module cannot reach out on its own. If it needs to print, read the clock or call the DOM, it declares an import, and you pass the implementation in an imports object shaped like { moduleName: { functionName: fn } }.

The module in the next demo imports env.log and exports logSquare(n), which squares its argument and calls log with the result. The imported function is declared with the same (i32) -> () type, so the JavaScript side receives a plain number:

JS Providing an import for the module

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the local function has index 1 in the export section: imported functions are numbered first, so log is function 0. This kind of detail is exactly why you let a compiler write modules for you, but seeing it once demystifies the format.

Linear memory

Numbers are easy to pass. Strings, arrays and structures are not, because Wasm only has numbers. The solution is linear memory: one big resizable block of bytes owned by the instance. A module can export it as a WebAssembly.Memory, and JavaScript sees it as an ArrayBuffer in memory.buffer. Both sides then communicate by writing bytes to agreed locations and passing the pointer (a number: the byte offset) and the length.

flowchart LR
  subgraph JS["JavaScript"]
    A["Uint8Array view<br/>on memory.buffer"]
  end
  subgraph W["Wasm instance"]
    B["exported function<br/>sum(ptr, len)"]
  end
  M[("Linear memory<br/>pages of 64 KiB")]
  A -->|"1. write bytes"| M
  A -->|"2. call sum(ptr, len)"| B
  B -->|"3. read bytes, return a number"| M

JavaScript writes into shared memory, passes a pointer and a length, and the module reads from the same bytes.

Memory is measured in pages of 64 KiB. The module below declares one page, exports it as memory, and exports sum(ptr, len), which adds up len bytes starting at ptr. JavaScript creates a typed array view over the memory (see Typed Arrays) to fill it:

JS Sharing memory between JavaScript and Wasm

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real toolchains generate this "glue" for you (for example wasm-bindgen for Rust, or Emscripten for C and C++), including functions to copy strings in and out and to allocate memory inside the module. Two rules still apply when you handle memory yourself:

  • Do not keep an old view after memory grows. memory.grow(pages) can move the data, which detaches the previous ArrayBuffer. Create a fresh new Uint8Array(memory.buffer) after any call that may grow memory.
  • Copying costs time. Crossing the boundary with large data is the usual reason a Wasm rewrite is not faster. Do the heavy work inside Wasm on data that stays in memory, and cross the boundary rarely, with simple values.

When to use WebAssembly

Reach for it when you have:

  • A big existing library in C, C++ or Rust (an image codec, a physics engine, a parser, a database) that you can compile instead of rewriting.
  • CPU-bound loops that dominate your profile: audio and video processing, compression, encryption, simulations.
  • Consistency across platforms, since the same module runs in browsers, in Node.js and in other runtimes.

Skip it when the slow part is the network, layout or the DOM, or when a small JavaScript change would do. The code is harder to debug, adds a build step, and the gains only show up when the work is heavy. Wasm can also run inside a Web Worker, which keeps the page responsive during long computations.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between a WebAssembly Module and an Instance?

    You can create many instances from one module, each with separate memory and state.
  2. 2. What does WebAssembly.instantiateStreaming(fetch(url)) require from the server?

    Streaming compilation checks the MIME type. Without application/wasm it rejects, and you can fall back to arrayBuffer() with instantiate().
  3. 3. How can a WebAssembly module print something to the console?

    A module is sandboxed and can only use the imports you provide, so output, clocks and the DOM all go through JavaScript functions.
  4. 4. How do you pass a string to a Wasm function that only accepts numbers?

    Wasm has only numeric types, so strings go through shared memory as bytes, described by an offset and a length.

Summary

  • WebAssembly is a compact binary format, usually compiled from Rust, C, C++ or Go, that runs safely in the browser at close to native speed and complements JavaScript.
  • Load bytes with fetch() and WebAssembly.instantiate(), or compile while downloading with WebAssembly.instantiateStreaming() (the server must send application/wasm). WebAssembly.validate() checks bytes quickly.
  • A Module is compiled code; an Instance has its own memory. The functions in instance.exports are called like normal JavaScript functions.
  • Wasm has four number types (i32, i64, f32, f64). Anything else, such as strings and arrays, travels through linear memory as bytes, with a pointer and a length.
  • A module can only call the imports you give it, and memory.grow() detaches old buffers, so recreate your typed-array views afterward.
  • Use Wasm for heavy, CPU-bound work or to reuse existing native libraries, and measure first.

Next: Project: To-Do App - put your JavaScript skills together in your first complete project.