Skip to content

Return 42 in WebAssembly Text Format via JavaScript

Open in GitHub Codespaces

To enable WebAssembly to be read and edited by humans, there is a textual representation of the Wasm binary format. This is an intermediate form designed to be exposed in text editors, browser developer tools, etc. This article explains how that text format works, in terms of the raw syntax, and how it is related to the underlying bytecode it represents — and the wrapper objects representing Wasm in JavaScript.

📚 You can read more about the WebAssembly Text Format on MDN

For instance, here's the WebAssembly Text Format code that exports a single function called answer() that returns the number 42:

wat
(module
  (func (export "answer") (result i32)
    i32.const 42
  )
)

To compile this text format into a binary .wasm file we can use wasm-tools parse:

sh
wasm-tools parse answer.wat -o answer.wasm

Tada! 🎉 Now we have an answer.wasm file which exports a single function called answer() which will return 42. We can run that answer.wasm anywhere in any WebAssembly runtime and it will work. We're going to use JavaScript in your browser to try it out:

js
// 1. Load the binary contents of the WebAssembly file.
///   If you were in Node.js you'd use 'fs.readFile()'.
const response = await fetch("answer.wasm");
const buffer = await response.arrayBuffer();

// 2. Compile the WebAssembly blob into a 'WebAssembly.Module'.
//    This will throw an error if the buffer isn't valid WebAssembly.
const module = await WebAssembly.compile(buffer);

// 3. Instantiate the module with any imports. We need none.
//    Normally you'd pass in things like a 'println()' function.
const importObject = {};
const instance = await WebAssembly.instantiate(module, importObject);

// 4. Call the exported 'answer()' function!
const { answer } = instance.exports;
console.log("The answer is:", answer());

Yes, normally you'd use WebAssembly.instantiateStreaming(). This is for demo purposes.

index.html
html
<script type="module" src="index.js"></script>
<p>Check the DevTools console!</p>

Now you can start your favorite dev HTTP server and open your browser to see the results! 🤩