How code execution works in Javascript?

Javascript is asynchronous, that simply means that it does not wait. Well, it does but not very often. And, unless you ask it to await.
Javascript is like the language of Web. So, if you planning to learn Web Development. Javascript is one of the things that you must consider learning. Although, you will be able to get multiple tutorials online that would teach you the semantics, syntax and programming in Javascript. But, most of them would skip over the fact that "Javascipt is single-threaded and asynchronous".
Single threaded model
Javascript being single-threaded,which means it has one memory heap and one call stack. So, that comes down to that you can only run a single task at a given time, and unti l then your program is stuck.
Consider the following code snippet:
1. console.log("One");
2. console.log("Two");
3. console.log("Three");
/*
Result:
One
Two
Three
*/
Here, Line 1 should finish executing before Line 2, and Line 2 should finish excuting before Line 3.
However, you must know that even though Javascript runs on a single thread. There are certain cases where Javascript behaves asynchronously. For example, see the below code snippet:
1. console.log("One");
2. setTimeout(() => console.log("Two"), 2000);
3. console.log("Three");
/*
Result:
One
Three
Two
*/
Here, this bit of code skips over Line 2, and executes Line 3 before Line 2 finishes. Now, that is asynchronous behaviour for you.
However for this to make sense to you. You must understand Javascript is an interpreted language and not a compiled language like Java, C or C++. There is no compilation step for Javascript, instead the code is interpreted line by line run by the interpreter. Modern intepretors in some enviornments use JIT (Just-in-Time) compilation, which convert Javscript code to executable code just when it is about to run.
V8 Engine written in C++ is used in Chrome and NodeJs enviornments to run Javascript. Firefox uses SpiderMonkey , which was introduced in 2017. IE and Edge had its own Chakra Engine. The newer Edge and all other chromium based browsers use V8 Engine under the hood.
These engine offers extra API features, which run the tasks in background while the Javascript keeps executing. In browser these external features are often referred to as Web APIs. In the example above, setTimeout() is an external API. So, whenever the browser encounters code using setTimeout it starts executing this snippet in background. And, when the task finishes it transfers the control back to Javascript.
For a deeper understanding of how this happens.
Event Loop in action: http://latentflip.com/loupe
List of available Web APIs: https://developer.mozilla.org/en-US/docs/Web/API





