Creating a Memory Object in JavaScript to Use in the Rust App

Learn how memory objects are created in JavaScript and used inside Rust.

Unlike JavaScript, Rust is not dynamically typed. The memory created in JavaScript has no way to tell WebAssembly (or the Rust code) what to allocate and when to free the memory. We need to explicitly inform WebAssembly how to allocate the memory and, most importantly, when and how to free it (to avoid any leaks).

We use the WebAssembly.memory() constructor to create the memory in JavaScript. The memory constructor takes in an object to set the defaults. The object has the following options:

  • initial: The initial size of the memory.

  • maximum: The maximum size of the memory (optional).

  • shared: To denote whether to use the shared memory.

The units for initial and maximum are WebAssembly pages, where a page refers to 64 KB.

We change the HTML file as follows:

Get hands-on with 1200+ tech skills courses.