Learn how to call a WebAssembly function from JavaScript with a simple example adding two integers using inline WAT compiled to WASM binary.
;; WebAssembly module in text format (WAT) defining an add function
(module
;; exports the 'add' function so it can be called from JavaScript
(func $add (param $a i32) (param $b i32) (result i32)
;; adds the two parameters
local.get $a
local.get $b
i32.add
)
(export "add" (func $add))
)
// JavaScript to load and use the WASM module
(async () => {
// Function to convert WAT text to WASM binary
const watToWasm = async (wat) => {
// Use WebAssembly.compileStreaming if available, otherwise fallback
if (typeof WebAssembly.instantiateStreaming === 'function') {
const encoder = new TextEncoder();
const wasmModule = await WebAssembly.compile(encoder.encode(wat));
return wasmModule;
} else {
// fallback: use an external or precompiled compiler
throw new Error('WAT compilation not supported in this environment');
}
};
// For simplicity, we use a precompiled inline array buffer (WASM binary)
// This is the compiled module of the above WAT (sum of two integers)
const wasmCode = new Uint8Array([
0x00,0x61,0x73,0x6d, // magic header
0x01,0x00,0x00,0x00, // version
0x01,0x07,0x01,0x60,0x02,0x7f,0x7f,0x01,0x7f,
0x03,0x02,0x01,0x00,
0x07,0x07,0x01,0x03,0x61,0x64,0x64,0x00,0x00,
0x0a,0x09,0x01,0x07,0x00,0x20,0x00,0x20,0x01,0x6a,0x0b
]);
// Instantiate the WASM module
const wasmModule = await WebAssembly.instantiate(wasmCode);
// Extract the add function from the exported module
const add = wasmModule.instance.exports.add;
// Call the add function with two numbers
const a = 5;
const b = 7;
const result = add(a, b);
// Print the result
console.log(`Result of add(${a}, ${b}) = ${result}`);
})();Arduino: Not applicable, software-only example.
Software: Node.js or modern browser with WebAssembly support.
Dependencies: No external libraries required.
Configuration: The WASM file must be properly loaded via fetch or import.
Connections: JavaScript uses WebAssembly.instantiateStreaming or WebAssembly.instantiate to load the WASM module.