Webassembly: the end of JavaScript?

I was shocked as you are when I read the same words on other blog posts, but digging deeper into the topic, I got a lot of new perspectives towards web development. In this article, we will learn what is Webassembly and create a very simple program to understand the key features and how it works in the browser.

What is webassembly?

Simply put webassembly is a way to write low-level code ( like C, CPP, rust ) that a browser can understand. The process involved is as follows.

  • write C code ( in this article ).
  • convert the code to a wasm file.
  • use fetch API to load the wasm file.
  • using javascript webassembly API to interact with wasm code.

we are going to dive deep into every steps listed above shortly.

Why webassembly?

Before we dive into the coding part, we need to understand whats the existing problem with javascript and how webassembly solves it.

When we say the problem with javascript, We are not referring to the vast features and library it has. Rather we see the way that javascript manages its memory allocation. Every high-level programming language comes with a garbage collection feature out of the box. Javascript being one uses the mark-and-sweep algorithm. Following are the steps on how javascript manages memory.

  • when js encounters a variable say, var a = 100 it allocates the memory for a.
  • the memory stays allocated till the variable has no other references (i.e, when no other function or variable using it).

If you have used any low-level language like C or CPP, you should take care of memory management. For example, in C you should use malloc() function for allocating memory dynamically and free()function to free the allocated memory. Technically you are doing the hard lifting for the language, this has its own advantages and disadvantages ( which is a topic for another article ) based on the requirements. The main advantage being you can program your code to use memory efficiently ( very efficiently ).

But in the case of a higher-level language, you cannot do much regarding memory management and it also consumes considerable resources. As a result, your application will get slower in execution. For this purpose, we use low-level code to solve some resource-intense problems. Example: game development, animation software, image processing, AR etcetera.

For so many years there were limitations with browsers executing such codes but with webassembly, there are numerous possibilities unlocked.

let’s dive into coding.

Project structure

In this article, we will create a simple application where we add two numbers in C and display it in the browser. There are only two files index.html( containing our js and HTML code ) and program.wasm( generated wasm code ).

Note: we will be using WasmFiddle, to compile our C code to wasm. You can also create a C file locally and generate wasm using Emscripten SDK, but for the sake of simplicity, we are using the online tool.

C program ( using WasmFiddle ):

Here we will code a simple function that takes in two params of type integer and returns the sum of it.

Webassembly-tutorial-wasmfiddle-interface
Wasm fiddle website
  • In the above window, we can see that we have a C function named simpleAdd(int a, int b) that accepts two params and returns its sum.
  • after writing the code you have to click the button for compiling the C code to wasm, if you have any errors with your code you will be notified in this step.
  • At first, the Js( on the top-right window ) will have a default code, replace that with the code above ( we will see in detail what the code means later in this article ).
  • At last click the button for checking if Js can read the compiled wasm code, if there is no error you will see “3” under the “output” section.

Now that we have tested our code, we now have to download the generated wasm file to execute locally. Click the button to down our wasm code, by default the name will be “program.wasm”.

Note: you will also see button, this will download the text form of our wasm file ( which you can find at the below-left section of the website ). This code is used for debugging wiz beyond the scope of this article.

Index.html:

Webassembly-tutorial-index-html-file
Index.html
  • We have a simple HTML file with two input elements for getting the numbers to perform an addition operation.
  • A button to calculate when clicked and an answer span tag to display our answer.
  • then we have fetch() function to load out generated “program.wasm” file.
  • Usually, if you have used fetch API before you would have converted the response to JSON, but here we are converting the response to an array buffer( as we are loading a wasm file not getting HTTP response ).
  • WebAssembly object ships with all the latest browsers so you don’t need to include an additional library. const compiledValue = await WebAssembly.instantiate(value, {});(the second parameter is for configuring memory, which is beyond the scope of this article. refer this link ) this line will load our array buffer value and return the content of the wasm file in a format that could be parsed by javascript.
  • Next, we add a click event for our button, and inside the callback, we have compiledValue.instance.exports.simpleAdd() function, this simpleAdd refers to the function that we created in our C program which accepts two params and returns their sum.

Result:

Webassembly-tutorial-result
Result

Enter two numbers in the text boxes and hit calculate button, the result will be displayed.

Possible errors:

You cannot directly open this html file in brower, you will be thrown with CORS origin error like below.

Webassembly-tutorial-cors-error
CORS Error

to handle this you can do one of the two things.

  • You can serve the “program.wasm” file using Nodejs with CORS enabled. ( Or )
  • The easy way if you are using vs code, you can use the Live server plugin for serving your folder from a server( this is only recommended for development purposes).

Conclusion:

So to answer the question Webassembly: The End Of JavaScript? absolutely Not. I will list out my opinions below.

  • Even though you can execute heavy code with webassembly, you still need Javascript to access the DOM.
  • Webassembly is not for everyone, most web apps can be built using javascript ( and its frameworks – btw you can check out my tutorial for AlpineJS and react-redux ) with high quality.
  • Webassembly is meant to work in conjunction with javascript not alone.

The market seems wide open for this technology as a matter of fact they are in use now and you might have used webassembly-built applications without knowing, you can check the list here. To name a few.

  • Unity
  • tensorflow.js ( the ML library ).
  • Google Earth
  • figma
  • autocad web ( web.autocad.com ).

Github repo: https://github.com/kishork2120/wasm_tutorial

Have fun coding!!!

13 thoughts on “Webassembly: the end of JavaScript?

  1. Thanks for the marvelous posting! I actually enjoyed reading it, you
    might be a great author.I will ensure that I
    bookmark your blog and will often come back
    in the foreseeable future. I want to encourage that you continue your great writing, have a nice afternoon!

  2. I feel that is among the so much important information for me.
    And i’m happy reading your article. But wanna observation on some basic
    issues, The site style is great, the articles is in reality excellent : D.

    Excellent process, cheers

  3. Howdy! Would you mind if I share your blog with my zynga
    group? There’s a lot of people that I think would really appreciate your content.

    Please let me know. Thank you

  4. Have you ever thought about adding a little bit more than just your articles?

    I mean, what you say is fundamental and everything. Nevertheless think of if you added some great graphics or video clips to give your posts more, “pop”!
    Your content is excellent but with pics and video clips, this site
    could certainly be one of the best in its field. Fantastic blog!

    1. Thanks a lot, man for the feedback and appreciation. Will definitely try to add videos clips and graphics.

  5. Excellent goods from you, man. I have understand your stuff prior to and you are just extremely great.
    I actually like what you’ve bought right here, really like what you are saying
    and the way in which through which you assert it. You are making it enjoyable and you continue to care
    for to keep it smart. I can not wait to learn much more from you.
    That is actually a terrific site.

  6. Very good info. Lucky me I ran across your website by accident (stumbleupon).
    I have book-marked it for later!

  7. Write more, thats all I have to say. Literally, it seems
    as though you relied on the video to make your point.

    You obviously know what youre talking about, why waste your intelligence on just posting
    videos to your weblog when you could be giving us something informative to read?

  8. Howdy! Quick question that’s totally off topic. Do you know
    how to make your site mobile friendly? My weblog looks weird when viewing from my iphone.
    I’m trying to find a template or plugin that might be able to
    resolve this problem. If you have any suggestions,
    please share. Many thanks!

  9. Hi there! This is my first comment here so I just
    wanted to give a quick shout out and say I genuinely enjoy reading
    your blog posts. Can you suggest any other
    blogs/websites/forums that go over the same topics? Appreciate
    it!

Leave a Reply to Kishor Kumar B M Cancel reply

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

Pin It on Pinterest

Translate »