Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 38 ยท Projects and Practice

WebAssembly Practice and Interview Questions

Practice WebAssembly with interview questions and answers, coding exercises with runnable solutions, trap-prediction drills, a debugging checklist and a self-assessment, covering memory, imports, WASI and performance.

This final lesson is a workout. It collects the questions that come up in interviews and code reviews, followed by coding exercises you can run and change, and a set of "what happens?" drills. Try to answer each question in your head (or aloud) before reading the answer; saying it in your own words is the best test of whether you understood.

The exercises build on what earlier lessons taught: modules and memory, the boundary between JavaScript and wasm, performance, WASI and security. If a question feels shaky, the link next to it points to the lesson that covers it.

Part 1: interview questions

Fundamentals

What is WebAssembly, in one paragraph? A compact binary instruction format for a stack-based virtual machine. It runs in browsers and other hosts at near-native speed, is validated before running, is sandboxed, and is a compile target for languages such as C, C++ and Rust. It complements JavaScript; it does not replace it.

Which value types does the core spec define? i32, i64, f32, f64, the 128-bit vector type v128, and reference types (funcref, externref). Everything else (strings, arrays, structs) is built from linear memory or, with the GC proposal, from managed types.

Why is WebAssembly called a stack machine? Instructions pop operands from and push results to an implicit operand stack: i32.add pops two values and pushes their sum. Structured control flow (block, loop, if) replaces arbitrary jumps, which makes validation fast and the format compact.

What is linear memory? One contiguous, growable, byte-addressable array owned by an instance, in pages of 64 KiB. All loads and stores are bounds-checked. It is the only place ordinary data structures live.

Can WebAssembly access the DOM? Not directly. A module can only call imports, so DOM access goes through JavaScript functions you pass in.

The boundary

How do you pass a string to a wasm function? Encode it as UTF-8, allocate space in the module's memory, copy the bytes, then pass the pointer and byte length. Free the memory afterward. See Passing Strings and Structs.

What happens to an i64 when it reaches JavaScript? It becomes a BigInt, and BigInt arguments are required for i64 parameters. See Other Languages for WebAssembly.

Why do typed-array views over memory.buffer sometimes become empty? memory.grow detaches the old ArrayBuffer, so any view created before the growth has length zero. Re-create views after anything that can grow memory.

What is the cost of calling wasm from JavaScript? Small but not zero: argument conversion and the transition. Many tiny calls waste time, so batch work and pass pointers to arrays. See WebAssembly Performance.

Performance

Is WebAssembly always faster than JavaScript? No. Hot numeric loops often are faster and more predictable, but optimized JavaScript can be close, and boundary crossings, copies and startup can erase the gain. Measure the whole task.

Name three ways to reduce a module's download size. Compile for size (-Oz, LTO, panic = "abort"), run wasm-opt and strip debug data, and serve with Brotli. Also avoid heavy dependencies. See Binary Size and Optimization.

What do SIMD and threads add, and what do they require? SIMD adds the v128 type for lane-wise operations; threads add shared memory and atomics. Threads on the web need cross-origin isolation headers (COOP and COEP). See SIMD and Threads.

Security and platforms

Why is running untrusted wasm reasonably safe? Validation up front, a bounds-checked private memory, a call stack the module cannot address, typed indirect calls and no ambient authority: the module can only use imports the host provides. See The WebAssembly Security Model.

Does the sandbox make C code compiled to wasm memory-safe? No. Bugs inside the module can still corrupt its own memory. The sandbox protects the host.

What is WASI and why does it use capabilities? A standard system interface for files, clocks, random numbers and more. The host grants specific resources (such as preopened directories), so a module has no more power than it was given. See What is WASI?

What does the component model add to core WebAssembly? Typed interfaces (strings, records, variants, results) described in WIT, a standard lift and lower ABI, and safe composition of components with separate memories. See The Component Model and WIT.

When would you not use WebAssembly? For DOM-heavy UI work, code dominated by network latency, tasks that need the full Linux environment, or when a team cannot afford the toolchain and debugging overhead for little measured gain.

Part 2: coding exercises

Exercise 1: assemble a function

Task: build, without any compiler, a module that exports max(a, b) returning the larger of two i32 values. Hint: the select instruction (opcode 0x1b) pops a condition and two values and returns the first value when the condition is non-zero. The solution below uses the little assembler from The WebAssembly Toolchain; try to write the body bytes yourself before reading them.

WAT
;; the target
(func (export "max") (param i32 i32) (result i32)
  local.get 0
  local.get 1
  local.get 0
  local.get 1
  i32.gt_s
  select)
Node.js Exercise 1: max(a, b) with select

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Things to try: change 0x4a (i32.gt_s) to 0x48 (i32.lt_s) and watch the tests fail; change it to 0x4b (i32.gt_u, an unsigned comparison) and see which test breaks and why (negative numbers look huge when read as unsigned).

Exercise 2: C strings and safe views

Task: write three JavaScript helpers for a module that exports memory and alloc: writeCString(text) (UTF-8 plus a terminating zero byte, returns a pointer), readCString(ptr) (reads until the zero byte) and getBytes(ptr, len) (a view that is safe even after memory growth).

Node.js Exercise 2: C strings and growth-safe views

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A real helper should also take a maximum length for readCString, because a missing terminator would otherwise scan the entire memory, a classic bug in C and in glue code.

Exercise 3: reasoning drills

For each snippet, decide the result before running it, then check yourself. This TryIt prints what really happens:

Node.js Exercise 3: what happens?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notes on the surprising ones: JavaScript numbers are converted to i32 with the ordinary modulo-2^32 rule, so 2**31 becomes -2147483648 and 2.9 becomes 2 (steps 4 and 5). Strings are converted to numbers before being passed (step 9). A missing BigInt for an i64 is a TypeError (step 6). The memory with initial larger than maximum is rejected at construction (step 10).

Part 3: debugging drills

For each symptom, name the most likely cause and the first check you would make.

Symptom Likely cause First check
LinkError: function import requires a callable The import object lacks a function the module needs WebAssembly.Module.imports(module) against your import object
CompileError: expected magic word The file is HTML or truncated (a 404 page, wrong path) Look at the first bytes and the response Content-Type
TypeError: Response has unsupported MIME type Server sends the wrong Content-Type Set application/wasm, or fall back to arrayBuffer()
RuntimeError: memory access out of bounds A bad pointer, wrong length or buffer overrun Hexdump the memory around the pointer; use -fsanitize=address
Text comes back truncated or garbled Character count used instead of UTF-8 byte length Print TextEncoder().encode(text).length
A typed array suddenly has length 0 Memory grew and the view is stale Create views after each call that can grow memory
unreachable with no message A Rust panic or C abort Install a panic hook; read console output before the trap
Fast in dev, slow in production Debug build deployed, or no compression or caching Check -O level, Content-Encoding and Cache-Control
SharedArrayBuffer is not defined Page is not cross-origin isolated Send COOP and COEP headers; check self.crossOriginIsolated

Part 4: self-assessment

Check each item. If you cannot do one, revisit the linked lesson.

  • I can explain linear memory, pages and why views go stale.
  • I can pass a string and an array to a module and read results back (strings and structs).
  • I can read a trap, use the name section, and set up source-level debugging (debugging).
  • I can shrink a module and explain what wasm-opt, stripping and Brotli each do (size).
  • I can load a module with streaming, cache it and run it in a worker (loading).
  • I can design a plugin host with an allow-list of imports and limits (plugins).
  • I can describe the security guarantees and their limits (security).
  • I can explain WASI capabilities and what the component model adds (WASI, components).
  • I can benchmark fairly and decide when Wasm is worth it (sieve project).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the select instruction, which value is returned when the condition is non-zero?

    select takes two values and a condition and returns the first value if the condition is non-zero, otherwise the second.
  2. 2. What does JavaScript pass to an i32 parameter when given the number 2.9?

    Numbers are converted with ToInt32, which truncates toward zero and wraps modulo 2^32.
  3. 3. A page throws SharedArrayBuffer is not defined when creating a shared memory. What is the usual fix?

    Shared memory requires cross-origin isolation, set up with Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy.
  4. 4. Why should readCString take a maximum length in production code?

    Untrusted or buggy data may lack a NUL byte. Bounded scans prevent runaway reads.
  5. 5. What is the most reliable way to learn which imports a module needs?

    The JS API reports every import's module, name and kind before you instantiate.

Summary

  • Be able to state, in plain words: what Wasm is, how memory and the boundary work, when it is faster, how it is made safe and how WASI and components extend it.
  • Practice by building small modules yourself; assembling bytes teaches the format better than any diagram.
  • Predict before you run: most interview-style surprises come from number conversion, BigInt, stale views and traps.
  • Keep a debugging table of symptom, cause and first check.

Next: back to the WebAssembly track page