Interacting with WebAssembly memory from JavaScript enables efficient data exchange, especially when dealing with complex or large datasets like arrays, buffers, or images. Although WebAssembly operates in its own memory space, you can bridge this gap by using its linear memory—a contiguous block of memory similar to an ArrayBuffer available in JavaScript. When you declare memory in WebAssembly, it behaves like an ArrayBuffer of a defined byte size. This memory is accessible both to Rust and JavaScript, and Rust’s Wasm bindings simplify the process of memory allocation and data transfer.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.


In this article, we demonstrate how to share data between WebAssembly and JavaScript. You will learn to transfer data from a JavaScript array into WebAssembly memory, modify it using a Rust function, and retrieve the updated values back in JavaScript.
Rust Function for Memory Manipulation
Below is the Rust function that modifies an array stored in WebAssembly memory. The function receives a pointer to the beginning of the array, the array’s length, and a value to add to each element. Notice the use of an unsafe block to convert the raw pointer into a mutable slice, effectively bypassing Rust’s safety checks.JavaScript Integration
On the JavaScript side, you begin by importing the initialization function (init) and the exported Rust function from the generated Wasm module. The init function loads the .wasm file, configures the module, and gives you access to its memory and functions. Below is an implementation example in an index.html file:
This script performs the following steps:
- Creates a JavaScript array.
- Allocates a corresponding segment in WebAssembly memory using a typed view (
Int32Array). - Copies the data from JavaScript into WebAssembly memory.
- Calls the Rust function to modify the array in place.
- Retrieves and logs the updated array from WebAssembly memory.
Summary of the Process
- Create a JavaScript array.
- Allocate the necessary space in WebAssembly memory.
- Populate the allocated memory with array data.
- Invoke a Rust function that modifies the array with direct memory manipulation.
- Retrieve and log the updated array from WebAssembly memory.
Starting a New Rust WebAssembly Project
For those looking to start a new Rust project using WebAssembly, the following command sets up a new library project:Direct memory access through WebAssembly is highly efficient when handling large datasets. Minimizing data copying between JavaScript and WebAssembly can notably boost performance, making it ideal for simulations, games, and intensive data processing tasks.
