WebAssembly Globals
A global is one value shared between JavaScript and Wasm. It can stay fixed, or it can change while the module runs.
A mutable counter global
This module exports a counter that starts at 0. Increment adds 1 to it.
(module
(global $counter (export "counter") (mut i32) (i32.const 0))
(func (export "increment")
(global.set $counter
(i32.add (global.get $counter) (i32.const 1))))
(func (export "getCount") (result i32)
(global.get $counter)))Read the counter from JavaScript
The counter starts at 0. After one increment it reads 1.
console.log(instance.exports.counter.value);
instance.exports.increment();
console.log(instance.exports.counter.value);Read the counter from Wasm
Two more increments make the count 3. GetCount reads the same global.
instance.exports.increment();
instance.exports.increment();
console.log(instance.exports.getCount());Example
(async () => {
const B64 = "AGFzbQEAAAABCAJgAABgAAF/AwMCAAEGBgF/AUEACwciAwdjb3VudGVyAwAJaW5jcmVtZW50AAAIZ2V0Q291bnQAAQoQAgkAIwBBAWokAAsEACMACw==";
const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
const { instance } = await WebAssembly.instantiate(bytes);
console.log(instance.exports.counter.value);
instance.exports.increment();
console.log(instance.exports.counter.value);
instance.exports.increment();
instance.exports.increment();
console.log(instance.exports.counter.value);
})();Key points
- A global is one value shared by both sides.
- An immutable global never changes after it starts.
- A mutable global can change while the module runs.
- JavaScript reads a global through its value property.
- Wasm reads a global with global.get.
In this example, the bytes are decoded and started into an instance. Then the code reads the counter, which starts at 0. One increment makes it 1, and two more increments make it 3.
Note
Wasm writes a mutable global with global.set.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
How does JavaScript read an exported Wasm global?