How Does JavaScript Work?


This is a basic question, but I bet most of you will have a hard time explaining the answer to an interviewer. Let's answer this question once and for all.
Just remember the below image.
How Javascript Works?
Now let me explain this image...
Every browser has its own Javascript engine like the V8 engine is a javascript engine for google chrome. Similarly, IE has Chakra , Firefox has SpiderMonkey. Let's concentrate on the Google Chrome V8 engine. In this diagram, the left side represents the V8 engine with Memory Heap (memory location where an object is stored) and Call Stack (which executes the program). The whole picture represents Javascript Runtime Environment. Now let's see with code how it works. Let's code along, press F12 to go to console tab and paste the below code:
  1. function hi(){  
  2.    let dummyVariable='hi';  
  3.    alert(dummyVariable);  
  4. }  
  6. hi()  
So you got Hi as an alert. What happens under the hood? In stack, the 1st the variable will be added and then the console.log(hi) will be added. You will now see a hi alert in your window. Once you click ok, then the console.log(hi) will be removed from the stack and the variable will be removed.
Now let's see another example:
  1. function hi(){  
  2.    let dummyVariable='hi';  
  3.    setTimeout(function(){alert('1st '+dummyVariable)},1000)  
  4.    alert('2nd '+dummyVariable);  
  5. }  
  7. hi()  
So, which one will run first, copy the code on the console, and you get a "2nd hi" and then a "1st hi". So what happened here, setTimeout (or any asynchronous call), the Javascript engine sees it, instead of putting it in the stack it sends it to the callback queue. So in the call stack, the 1st dummyVariable is loaded and then the stack sees timeout and does not load in the stack. Instead, it sends to callback queue (away from V8 Engine) and then alert ('2nd '+dummyVariable); is put in the stack and you will see an alert with "2nd Hi", setTimeOut will wait in the callbackqueue until the event loop puts it in the call stack. The event loop constantly checks the stack whether it is free or not. Once it sees it's free, it will add it to stack and you will get an alert "1st Hi". That's it.

Next Recommended Reading Working with DateTime in JavaScript