What happens when you run a JavaScript code?
JavaScript code runs on a JavaScript runtime — browser that you use. JavaScript runtime uses JavaScript engine which converts the JavaScript code to machine code. JavaScript engine for Chrome and node is V8, for Mozilla — SpiderMonkey, for Safari — Nitro, and for IE — Chakra.
JavaScript engine consists of a memory heap and a call stack. The memory heap stores all the variables defined in our JavaScript code while the call stack performs the operations (function execution). JavaScript runtime provides additional features such as event listeners, HTTP/AJAX requests, or timing functions, etc. to support execution of the JavaScript code.
JavaScript is single threaded, non-blocking, asynchronous and concurrent programming language.
As we look into the JavaScript definition, we will find that JavaScript is Single Threaded which implies that it only has one Call Stack. One Call Stack implies only one piece of code can be executed at a time. When a function is pushed into the call stack, then the execution context of the JavaScript code is the function on the top of the call stack.

JavaScript is also known for it’s non-blocking behavior. Non-blocking means that JavaScript doesn’t wait for the response of an API call, an Ajax request, an I/O event or a timer but moves on with the other block of code below it. But how is JavaScript non-blocking when it only has one thread? The answer is that these requests are performed by web APIs (C++ library in case of node) which has its own thread. This makes concurrency possible in JavaScript.
As we know, when a function with asynchronous callback is called, the function call is pushed to the Call Stack. And, when an asynchronous call is made to the Web API within that block of function, the request is transferred to the web APIs and the function call is popped out of the call stack. A new task is then pushed to the call stack and is executed. Meanwhile, the Web API performs the request.
On the Web API side, on completion of the HTTP request, the callback function is sent to the callback queue (event queue). These callback functions stay in the callback queue as long as the Call Stack is not empty. Once the call stack becomes empty, the callback function at the beginning of the callback queue is pushed to the call stack and the JavaScript engine starts executing that block of the callback function.
Callback queue is simply a staging area where the callback functions are waiting to be invoked and moved over to the call stack.
How does the runtime knows that the call stack is empty and how is the events in the callback queue invoked? All of these are performed by an Event Loop.

Event Loop is a process that constantly keeps on checking if the call stack is empty and if it is, it checks whether there is an event in the callback queue waiting to be invoked.
Event loop moves the first event from the even queue to the empty call stack. The event loop keeps on running indefinitely even if the callback queue is empty (but this is not the case in node).

Conclusion
- JavaScript is single threaded because it has only one call stack where the function is executed.
- Execution context is the function on the top of the call stack which is being executed at the moment.
- JavaScript is non-blocking because the slow processes which require call to the Web API are executed in the Web API leaving the call stack open for other function execution.
- JavaScript is executed concurrently because the Web API handles the calls made to it while the JavaScript engine keeps executing other block of the code.
- JavaScript, though it is synchronous, behaves asynchronously because the web API adds the callback to the callback queue (event queue) which then pushes the callback to the call stack for execution.
- Event loop checks for the events in the callback queue and pushes it to the empty call stack.
What does Single Threaded & Non-Blocking mean in JavaScript?
What is single-threaded mean?
Javascript is a single-threaded language. This means it has one call stack and one memory heap. As expected, it executes code in order and must finish executing a piece code before moving onto the next. So if we print from 1to 5 it will execute every line one by one and can’t execute all prints at a single time.
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
Execute line 1 & Print => 1
Execute line 2 & Print => 2
Execute line 3 & Print => 3
Execute line 4 & Print => 4
Execute line 5 & Print => 5
What is Non-Blocking?
console.log("Started");
//AJAX REQUEST FOR GOOGLE.COM
var google = $.getSync("https://www.google.com")
console.log("Ended");
Here getSync function making ajax request to google.com, which is blocking the process. If we execute this code in C, PHP or any other language it will execute like this.
Print => Started
Call Google.com and wait for few seconds
After fetching data from google.com goto next line
Print => Ended
In our core languages(C, PHP), this code executes like this because they are blocking language & as we know according to our definition JavaScript is a non-blocking language, getSync function call doesn’t stop our rest of the code to execute and print “Ended” before fetching data from google.com, like this
Print => Started
Call Google.com and removed from the stack as it is taking time to execute
Print => Ended
After fetching data from google.com code execution completed.
So now we got the idea of why we call JavaScript as non-blocking. In the next edition, I will tell you about the Queue, Event loop and Web APIs. Keep reading.
JavaScript. Event Loop and Promises
Promises, that new type of object that appeared (finally) natively with the arrival of ES6 and that allows us to perform tasks asynchronously to, once completed, obtain the result of them ( or a fault if it occurred) and execute the code we need. But then … is Javascript asynchronous? Well, to answer this question we will also delve into the “tool” known as Event Loop and that so often appears in the questions that the selection technicians ask in the interviews
Let us start from the base that Javascript is synchronous and has a single thread of execution. That is, it is only capable of executing one task at a time which blocks the execution until it is finished and can proceed to the next one.
However … what happens when we have to execute a heavy query? For example, obtain a list of 10,000 records with which we will work later. Is there no way to prevent execution from being blocked so that while we can continue doing other tasks? This is where the solution proposed by the developer community appears in order to provide Javascript with a certain aspect of asynchronousity: the famous Event Loop.
Therefore, although Javascript is not asynchronous, the inclusion of the WebAPI together with the Event Loop and the Queue Callback allow it to provide a certain aspect of asicronicity so that the heavier tasks do not block the thread of execution.
However, there is a “but”. Since the callback of the function is not known at what time it will be executed (since as we have seen it is necessary that the stack is left empty so that the Event Loop can add things to it from the queue callback) it may be necessary Nesting successive calls within the callback of our function, something known as the “hell callback”.
It is to solve this for what promises arose as we will see below.

Promises
In order to avoid this “callback hell”, a series of libraries such as Bluebird or Q were developed that allowed to clean a little all that tangle of nested functions and write code that operated asynchronously but that seemed written as if it were synchronous: the Promises were born .
Subsequently, with the arrival of ES6, the proposal to bring Promises to Javascript natively was accepted, leaving its syntax as follows:
const p = new Promise(function(resolve, reject) {
return setTimeout(function() {
resolve(1);
}, 10000);
});
p.then(function(value) {
console.log(value)
});
// 1
We can define a Promise as an object that can produce a single value at some time in the future, either a value or the reason why it could not be resolved.
A Promise can be in three states: pending, fulfilled or rejected. To these Promise objects, developers can attach callbacks through the then instruction so that we can execute code once the value resolved by the Promise is available (or the reason why it could not be resolved).
In addition, another characteristic of the Promises is that they are eager, that is, a Promise will begin to do the task that resides in your body so Soon as the constructor is invoked. You can see it in this example:
The Message Queue
When setTimeout() is called, the Browser or Node.js start the timer. Once the timer expires, in this case immediately as we put 0 as the timeout, the callback function is put in the Message Queue.
The Message Queue is also where user-initiated events like click or keyboard events, or fetch responses are queued before your code has the opportunity to react to them. Or also DOM events like onLoad.
The loop gives priority to the call stack, and it first processes everything it finds in the call stack, and once there’s nothing in there, it goes to pick up things in the message queue.
We don’t have to wait for functions like setTimeout, fetch or other things to do their own work, because they are provided by the browser, and they live on their own threads. For example, if you set the setTimeout timeout to 2 seconds, you don’t have to wait 2 seconds – the wait happens elsewhere.
ES6 Job Queue
ECMAScript 2015 introduced the concept of the Job Queue, which is used by Promises (also introduced in ES6/ES2015). It’s a way to execute the result of an async function as soon as possible, rather than being put at the end of the call stack.
Promises that resolve before the current function ends will be executed right after the current function.
I find nice the analogy of a rollercoaster ride at an amusement park: the message queue puts you at the back of the queue, behind all the other people, where you will have to wait for your turn, while the job queue is the fastpass ticket that lets you take another ride right after you finished the previous one.
Example :
const bar = () => console.log('bar')
const baz = () => console.log('baz')
const foo = () => {
console.log('foo')
setTimeout(bar, 0)
new Promise((resolve, reject) =>
resolve('should be right after baz, before bar')
).then(resolve => console.log(resolve))
baz()
}
foo()
//Output :
foo
baz
should be right after baz, before bar
bar
That’s a big difference between Promises (and Async/await, which is built on promises) and plain old asynchronous functions through setTimeout() or other platform APIs.
