Senior LevelJavaScript & TypeScript
How do WebAssembly (Wasm) modules interface with JavaScript memory and typed arrays?
❓ Interview Prompt: Explain WebAssembly.Memory, ArrayBuffer shared linear memory, passing pointers between JS and Wasm, and text decoding.
WebAssembly (Wasm) executes compiled low-level C++/Rust/Go code at near-native speed inside the JavaScript engine.
Memory Interoperability:
•
Wasm and JS share memory via a linear memory array (
WebAssembly.Memory), which wraps a JavaScript ArrayBuffer.•
JS reads/writes Wasm memory directly using TypedArrays (
Uint8Array, Float32Array).•
Passing complex structures (strings, objects) requires writing bytes into Wasm linear memory and passing the memory pointer (integer offset) to Wasm functions!
Code Implementation Example
javascript
// Instantiating WebAssembly linear memory
const memory = new WebAssembly.Memory({ initial: 1 }); // 1 page = 64KB
// JS TypedArray viewing Wasm linear memory
const bytes = new Uint8Array(memory.buffer);
// Passing string to Wasm: encode bytes into memory buffer
const encoder = new TextEncoder();
const stringBytes = encoder.encode("Hello Wasm");
bytes.set(stringBytes, 0); // Write string to offset 0
// Wasm function call receives pointer offset (0) and length
// wasmInstance.exports.processString(0, stringBytes.length);💡WebAssembly linear memory sharing via ArrayBuffer and TypedArray pointer offset manipulation.
🎯 Interview Key Takeaway
JavaScript and WebAssembly communicate across a shared linear ArrayBuffer using memory pointers and TypedArray views.
#WebAssembly#Wasm#ArrayBuffer#Senior
Back to all JavaScript & TypeScript Questions→