🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly Hello World

WebAssembly Hello World is a first tiny module that adds two numbers. WAT is the readable text form of WebAssembly, and a module is one packaged unit of WebAssembly code.

The whole module

This is the full add module in WAT.

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

Add 2 and 3

This call runs the add function with 2 and 3.

console.log(instance.exports.add(2, 3));

Add 40 and 2

This call runs the same function with 40 and 2.

console.log(instance.exports.add(40, 2));

Example

const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAgEABwcBA2FkZAAACgkBBwAgACABags=";
(async () => {
  const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
  const { instance } = await WebAssembly.instantiate(bytes, {});
  console.log('2 + 3 =', instance.exports.add(2, 3));
  console.log('40 + 2 =', instance.exports.add(40, 2));
})();

Key points

  • WAT: the readable text form of WebAssembly.
  • Module: one packaged unit of WebAssembly code.
  • Func: one block of steps inside a module.
  • Param: one input value a function takes in.
  • Result: one output value a function gives back.
  • i32: one whole number held in 32 bits.
  • Use (export "add") to make the add function callable from a page.
  • Use local.get 0 to read the first input value.
  • Use i32.add to add two whole numbers together.

In this example, the first line holds the module bytes as text. The next line turns that text into bytes. Then the code builds the module and waits for it. Then it calls add with 2 and 3. Then it calls add with 40 and 2. The two lines print 5 and 42. One small module can add any two numbers.

Note

The WAT file is text. The browser runs the compiled bytes, not the text.

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

What does instance.exports.add(2, 3) give back?