Web Assembly (Wasm) with JavaScript


Have you ever wondered if it's possible to run high-performance applications on the web without sacrificing the portability and security that JavaScript provides? Well, wonder no more! With the introduction of WebAssembly (Wasm), it is now possible to bring native-like performance to web applications while still leveraging the power of JavaScript. In this article, we will explore the basics of WebAssembly and how it can be used alongside JavaScript to unlock a new world of possibilities.

What is WebAssembly (Wasm)?

WebAssembly, often referred to as Wasm, is a binary instruction format designed specifically for web browsers. It is a low-level virtual machine that enables the execution of code at near-native speed. Wasm was developed as a collaborative effort between major browser vendors such as Mozilla, Google, Microsoft, and Apple, with the goal of bringing high-performance applications to the web.

One of the key advantages of WebAssembly is that it is compatible with multiple programming languages, making it a versatile solution for web development. You can write code in languages like C++, Rust, and even TypeScript, and then compile it to the Wasm binary format, which can be executed directly in the browser.

Integrating WebAssembly with JavaScript

WebAssembly brings a plethora of benefits to web development. It allows developers to execute computationally intensive tasks at near-native speeds, making it suitable for applications that require high-performance execution. By leveraging WebAssembly, developers can port existing codebases written in languages like C++, Rust, or TypeScript to the web without sacrificing performance.

The integration of WebAssembly with JavaScript enables seamless interaction between the two languages. JavaScript acts as a bridge, providing a convenient interface for working with WebAssembly modules. This allows developers to combine the power of WebAssembly with the rich ecosystem and flexibility of JavaScript libraries and frameworks.

Although WebAssembly is a standalone technology, it can seamlessly integrate with JavaScript, allowing developers to combine the strengths of both languages in a single application. JavaScript acts as the glue between the web platform and WebAssembly modules, providing a convenient interface for interacting with the compiled code.

JavaScript provides the necessary APIs to load the WebAssembly module. The fetch API is used to retrieve the binary file, and the resulting ArrayBuffer is passed to the WebAssembly.instantiate function. This function asynchronously compiles the module and returns an instance that contains the exported functions and memory of the module. By accessing these exported functions, JavaScript can invoke the functionality provided by the WebAssembly module.

To demonstrate this integration, let's consider a simple example. We'll write a Wasm module that calculates the Fibonacci sequence, and then we'll call this module from JavaScript.

Step 1: Writing the WebAssembly Module

Let's start by writing the Fibonacci calculation logic in C++. Save the following code in a file named fibonacci.cpp −

#include <emscripten.h>

extern "C" {
   int EMSCRIPTEN_KEEPALIVE fibonacci(int n) {
      if (n <= 1) {
         return n;
      } else {
         return fibonacci(n - 1) + fibonacci(n - 2);
      }
   }
}

Explanation

In this code, we have a C++ function fibonacci that calculates the Fibonacci sequence recursively. The EMSCRIPTEN_KEEPALIVE macro is used to ensure that the function is exported and can be accessed from JavaScript.

Step 2: Compiling the WebAssembly Module

To compile the C++ code into WebAssembly, we'll use the Emscripten toolchain. Run the following command in the terminal −

emcc fibonacci.cpp -s WASM=1 -o fibonacci.wasm

This command will generate the fibonacci.wasm file, which contains the compiled WebAssembly module.

Step 3: Calling WebAssembly from JavaScript

Now that we have our WebAssembly module, let's call it from JavaScript. Save the following code in an HTML file, index.html −

Example

<!DOCTYPE html>
<html>
<head>
   <script>
      const fetchAndInstantiate = async () => {
         const response = await fetch('fibonacci.wasm');
         const buffer = await response.arrayBuffer();
         const module = await WebAssembly.instantiate(buffer);
         const instance = module.instance;

         const fibonacci = instance.exports.fibonacci;
         const result = fibonacci(10);

         console.log('Fibonacci(10):', result);
      };

      fetchAndInstantiate();
   </script>
</head>
<body>
</body>
</html>

Explanation

In this code, we use the fetch API to retrieve the fibonacci.wasm file and convert it into an ArrayBuffer. We then instantiate the WebAssembly module using WebAssembly.instantiate and obtain the exported fibonacci function from the module's instance. Finally, we call the fibonacci function with the argument 10 and log the result to the console.

Step 4: Running the Example

To run the example, open the HTML file in a web browser. Open the browser's developer console, and you should see the output Fibonacci(10): 55. This confirms that the WebAssembly module was successfully loaded and executed from JavaScript.

Conclusion

WebAssembly is a powerful technology that opens up new possibilities for high-performance web applications. By combining the strengths of WebAssembly and JavaScript, developers can leverage existing codebases, write performance-critical parts in lower-level languages, and seamlessly integrate them into their web projects. With the flexibility and portability of WebAssembly, the web platform is poised to become an even more capable environment for running complex applications.

Updated on: 25-Jul-2023

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements