DEV Community

Rakesh
Rakesh

Posted on • Updated on

How does javascript really work : a peek under the hood..

Javascript can be found everywhere nowadays ,from browser to server, from mobile to desktop, even in hybrid apps as well. Also It has a vast community behind it with an equally incredible eco-system which is contineously evolving in a proper way .

All of this led it to become one of the most preferred language to learn for newbies like me for getting a job in near future . But a lot of us never try to find out how it is actually working behind the scene , unless they have a interview scheduled next week .

That's why this article is an attempt to give everyone a heads up about the basics ..so without further ado ..let's get going then..

Have you ever thought how come all the modern browsers understand javascript ? who is translating it for them ?

They all have something similar...A Javascript Engine built into them...

What Is Javascript Engine now ?

A Javascript Engine nothing but a program written normally in C and C++ , which goes through the javascript code one line at a time and convert it to the machine readable format so that the cpu can understand and execute it .

Some famous javascript engines are :

  • V8 – engine used in Opera & Chrome.
  • SpiderMonkey – engine used in Firefox.
  • SquirrelFish – engine used in Safari.

Ok, So What's in this Engine ?

It is mainly consist of two main parts :

  • Memory Heap
  • Call Stack

js engine.png

What are those now ?

  • Memory Heap- Whenever you define a variable, constant,
    object,etc in your javascript program, you need some place to
    store it first , That place is nothing but the memory heap.

    So Whenever we define a variable likevar a = 10, a
    location in the memory is assigned to store the value of a.

    However there is something important here to remember , the
    available memory in Memory Heap is limited . So even if
    Javascript offers a effective garbage collection mecanism
    automatically, Memory leaks can still occur due to various
    reasons like Using Global Variables or Using Too Many Event
    Listeners etc etc.

  • Call stack - The Call Stack is nothing but a data
    structure,which records basically where in the program we are.
    As JavaScript is a single-threaded programming language, it
    has only one Call Stack .

    Which means whenever we execute a function i.e we put it on
    the top of the stack or when we return from a function i.e we
    pop it off from the top of stack , all of it happens one at a
    time.

    Call stack size is also limited like Memory Heap . So whenever
    a program attempts to use more space than there is available,
    Stack Overflow occurs .

Why does Javascript choose to be single threaded ?

Because it is easy and less complicated than multi-threaded environment,
where sometimes you have to deal with scenarios like Deadlocks and all .

But isn't it limiting ? What's gonna happen when things are slow ?

Yes . If we process things like image processing or network request synchronously, It can be a cause of browser getting stuck or block .
And that's not the only problem you are going to encounter here . Once the browser starts to process all the remaining tasks, It may stop being responsive for a quite long time .

I think all of you must remeber this page unresponsive error .

008Ah.jpg

So How to prevent Blocking then ?

Well , the answer is Asynchronous Callbacks .

Wait , you just said it is a single threaded langunage,then how does it handle Asynchronous Callbacks ?

Well it turns out I have been telling you partial truth this whole time . There's more to the browser than just the engine . It also consist of Event Loop and Call back Queue along with various Web APIs like the DOM,
AJAX (XMLHttpRequest), setTImeout() and many more .

jre.png

So, you are saying setTimeout() is not a part of javascript then ?

Yes , Technically it's not a part of javascript engine . As it provided by the
Web APIs .

Can you give us a example ?

Sure , Consider the following the codes..

console.log('1');
setTimeout(()=>{
   console.log('2');
},5000);
console.log('3');
Enter fullscreen mode Exit fullscreen mode

As you all know, the output gonna be like this

1
3
2
Enter fullscreen mode Exit fullscreen mode

but do you know how does it arrive at this output ...let me walk you through this ..step by step..

first.png

second.png

third.png

fourth.png

Five seconds later...

fifth.png

sixth.png

seventh.png

I have a doubt , What if the setTimeout() is set to 0 ?

The result is still going to be same , As the callback by any means not going to pass through the Event Loop untill the stack is complete empty .

Ok,.this looks interesting , Where can I find out about this more ?

I have choose to not going into too much depth about it because if you are only starting out it might be overwhelming for you already . But for those who are into the game a little bit longer, I believe the following resources can help them for sure .

https://medium.com/better-programming/how-javascript-works-1706b9b66c4d

https://blog.bitsrc.io/how-does-javascript-really-work-part-1-7681dd54a36d

https://www.youtube.com/watch?v=8aGhZQkoFbQ&feature=emb_title

Top comments (2)

Collapse
 
khusharth profile image
Khusharth A Patani

Amazing blog! The diagrams made your explanation super clear.

Collapse
 
rakesh profile image
Rakesh

Guys I am very new to the world of web dev..this is literally my first article..so It would mean so much to me ..If you spare a minute to tell me what do you think about the article...