← Back to Lessons Lesson 3 of 48
Beginner getting-started
Hello WebAssembly
Introduction
WebAssembly (Wasm) lets you run compiled code in the browser at near-native speed. Rust is one of the best languages for targeting Wasm because of its zero-cost abstractions, no garbage collector, and small binary sizes.
How It Works
- You write Rust code and annotate functions with
#[wasm_bindgen] - The
wasm-packtool compiles your Rust code to a.wasmbinary - JavaScript can import and call your exported functions directly
Key Concepts
#[wasm_bindgen]— marks functions to be accessible from JavaScript&str— Rust's string slice type, automatically converted from JS strings- Return types — Rust types like
String,i32,f64are converted to JS equivalents
Calling from JavaScript
Once compiled with wasm-pack, you can import and call your Rust functions directly:
import init, { greet, add } from './pkg/hello_wasm.js';
async function run() {
await init();
console.log(greet("World"));
console.log("2 + 3 =", add(2, 3));
}
run();Why two imports? init vs { greet, add }
Every Wasm module has two kinds of imports:
import init, { greet, add } from './pkg/hello_wasm.js';
// ^^^^ ^^^^^^^^^^^^^^
// │ └── Named exports: your Rust functions and structs
// └── Default export: the Wasm initializerinit (default export):
- Downloads and compiles the
.wasmbinary file - Must be called once before using any Rust function
- Returns a
Promise— useawait init()or.then() - After this call, all named exports are ready to use
{ greet, add } (named exports):
- Your
#[wasm_bindgen] pub fnfunctions - Your
#[wasm_bindgen] pub structtypes (as JS classes) - These are not usable until
init()completes
This is why Wasm code always follows this pattern:
// Step 1: Initialize (downloads + compiles .wasm)
await init();
// Step 2: Now use your Rust functions
greet("World"); // ✓ works
add(2, 3); // ✓ worksIf you try to call a function before init():
greet("World"); // ✗ Error: Wasm not initialized
await init();
greet("World"); // ✓ Now it worksTry It
Modify the greet function to include a personalized message, or add a new exported function like multiply.
Try It
Chapter Quiz
Pass all questions to complete this lesson