🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly AssemblyScript Tutorial

AssemblyScript compiles TypeScript-like code straight to WebAssembly. Its compiler is called asc.

Install and compile

Install the compiler, then compile one file.

npm install assemblyscript
npx asc add.ts --outFile add.wasm

Add two numbers

This function takes two integers and returns their sum.

export function add(a: i32, b: i32): i32 {
  return a + b;
}

Double a number

Small helpers look the same as in TypeScript.

export function double(n: i32): i32 {
  return n * 2;
}

Example

const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAgEABQMBAAAHEAIDYWRkAAAGbWVtb3J5AgAKCQEHACAAIAFqCw==";
(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

  • AssemblyScript is a language shaped like TypeScript.
  • Use asc to compile a file into a module.
  • The output has no runtime, so the module stays small.
  • JavaScript developers face the lowest learning curve here.
  • The demo module below is the same add function compiled by asc.
  • TypeScript-like code becomes a module the browser can run.

In this example, the code decodes the module bytes from B64 and instantiates the module. It calls add with 2 and 3 and logs the sum. Then it calls add with 40 and 2 and logs that sum.

Note

AssemblyScript needs a type on every value.

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

Why is AssemblyScript easy for JavaScript developers?