← Back to Lessons Lesson 3 of 8
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();Try 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