WebAssembly(WASM) in JavaScript

WASM also known as WebAssembly, was introduced in 2017 as a binary instruction format designed for a stack-based virtual machine. Its primary purpose is to run efficiently within modern web browsers. WASM is a low-level assembly language format that can be compiled from various languages like C++, C#, Rust, and even JavaScript. It acts as a portable target for code execution, allowing efficient and near-native performance within web browsers. WASM code is not directly JavaScript, but it can be loaded and executed alongside JavaScript within the same web page.

 JavaScript interacts with WASM modules through specific API functionalities:

 

  1. Loading WASM modules:
  • Fetching bytecode: JavaScript uses the fetch API to retrieve the WASM bytecode from a server location (similar to fetching other resources like images or scripts).
  • Instantiating the module: Once the bytecode is downloaded as an ArrayBuffer, the WebAssembly.instantiate function is used to create a WASM module instance. This process involves validating the bytecode, allocating memory, and preparing the module for execution.

2. Calling WASM functions:

  • Accessing exports: WASM modules can export functions, similar to how JavaScript modules can export functions.
  • Retrieving exported functions: JavaScript uses the instance.exports property of the WASM module instance to access the exported functions. These functions are then callable like any regular JavaScript function.

3. Passing data between them:

  • Data types: Both JavaScript and WASM have their own data types, but they need to be compatible for communication.
  • Marshalling and unmarshalling: This refers to the process of converting data between JavaScript types and WASM types. Libraries like emscripten simplify this process by automatically handling data marshalling and unmarshalling during function calls.
  • Arguments and return values: When calling a WASM function from JavaScript, arguments are passed through the function call, and the returned value is also converted back to a compatible JavaScript type for use in further processing.

 

Memory sharing: Both JavaScript and WASM can share a common memory space, allowing them to access and modify the same data structures. This enables efficient data exchange between the two environments.

Asynchronous nature: Loading and instantiating WASM modules can be asynchronous operations, so JavaScript needs to handle them using promises or async/await patterns to ensure proper execution flow.

By leveraging these functionalities, JavaScript can effectively interact with WASM modules, extending its capabilities for performance-critical tasks and integration with existing codebases.

Leave a comment

Your email address will not be published. Required fields are marked *