Calling Closures via WebAssembly

Learn how to call Closures using WebAssembly.

What is Closures?

The official Rust book, by Steve Klabnick and Carol Nichols, defines Closures as follows:

“Closures are anonymous functions which you can save in a variable or can be passed as arguments to other functions.”

MDN defines a closure for JavaScript as follows:

“A closure is the combination of a function and lexical environment within which that function was declared.”

In general, Closures are self-contained blocks of functionality that are tossed around and used in the code. They can capture and store references to the variables from the context in which they’re defined. Closures and functions are similar except for a subtle difference. Closures will capture the state when it’s first created. Then, whenever a Closure is called, it closes over that captured state.

Closures are functions with a state. When you create a Closure, it captures the state. Then, we can pass around closures just like any other function. When a Closure is then invoked, it closes over this captured state and executes (even when the Closure is invoked outside of its captured state). That is one of the important reasons why the use of Closures is increasing on the functional side of JavaScript. Closures make it easy to do data encapsulation, higher-order functions, and memoization. (Sounds functional, right?)

Getting started with a project

Let’s see how to share Closures from JavaScript to Rust and vice versa:

  1. Create a new project:

Get hands-on with 1200+ tech skills courses.