Exploring WebAssembly (WASM)
WebAssembly Core Concepts
Memory and Tables
In the WebAssembly ecosystem, two core components—memory and tables—provide structured storage and dynamic function lookup. Think of your application as a city:
- Memory is the land where data “buildings” (variables, arrays, structs) stand.
- Tables are the city directory listing services (function references) for quick access.
WebAssembly Memory
WebAssembly memory is a sandboxed, growable linear buffer of bytes. It holds everything from your module’s numeric data to string buffers.
Feature | Description |
---|---|
Continuous | Represented as one contiguous array of bytes |
Resizable | Can be expanded at runtime (within limits) |
Isolated | Sandboxed to prevent corruption of the host or other modules |
Note
Out-of-bounds memory accesses in WebAssembly always trap, ensuring that modules cannot read or write arbitrary host memory.
You can define memory in your .wat
module like this:
(module
(memory $mem 1 2) ;; initial size = 1 page (64KiB), max size = 2 pages
;; ...
)
And from JavaScript:
const wasm = await WebAssembly.instantiateStreaming(fetch('module.wasm'));
const memoryBuffer = new Uint8Array(wasm.instance.exports.memory.buffer);
// Read or write to memoryBuffer as needed
WebAssembly Tables
Tables are lookup structures for function references (and, with the reference types proposal, external references). They don’t contain code—only pointers—enabling indirect calls and dynamic dispatch.
For instance, define a table of funcref
entries:
(module
(table $t 2 funcref) ;; table with 2 function slots
(elem (i32.const 0) $f1 $f2) ;; initialize slots
(func $f1 (result i32) (i32.const 42))
(func $f2 (result i32) (i32.const 100))
(func (export "call_indirect") (param i32) (result i32)
(call_indirect (type $t) (local.get 0))
)
)
When you call call_indirect
with 0
or 1
, WebAssembly jumps to $f1
or $f2
respectively—just like dialing a number on a menu.
Warning
If you call an uninitialized or out-of-bounds table index, WebAssembly will trap immediately.
With the externref
feature, tables can also hold references to host objects (e.g., JS DOM nodes or game entities). This powerful extension enables seamless interoperability between WebAssembly modules and their host environment.
Summary
WebAssembly’s memory and tables provide:
- Secure, linear storage for all data
- Dynamic, sandboxed function dispatch
- Runtime growth and module evolution without rewriting callers
Mastering these primitives is essential for building high-performance, modular WebAssembly applications that integrate smoothly with JavaScript or other host environments.
Further Reading
Watch Video
Watch video content