🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly vs JavaScript

JavaScript and WebAssembly split the work on a web page. JavaScript runs the page, and WebAssembly runs the heavy computing.

JavaScript handles the page

A click changes a heading with plain JavaScript.

const heading = document.querySelector("h1");
heading.textContent = "Hello";

JavaScript handles a small job

A small sum needs no extra module.

function add(a, b) {
  return a + b;
}
console.log(add(2, 3));

Example

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

Key points

  • Use JavaScript for buttons, forms, and page changes.
  • Use WebAssembly for heavy maths, pixels, and sound.
  • JavaScript talks to the page directly, and WebAssembly does not.
  • A small job runs faster in plain JavaScript than in WebAssembly.
  • A big job runs faster in WebAssembly than in plain JavaScript.

In this example, JavaScript adds 2 and 3, and then a WebAssembly module adds the same two numbers. Both answers are 5. The two tools share the work, and each one does the part it fits best.

Note

Pick the tool that fits the job, not the newer tool.

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

A page needs a button click to change a heading. Which tool fits best?