Photo by Gabriel Heinzer on Unsplash
In-Depth Javascript
Let's learn what happens behind the scenes in JavaScript
You may ask, What is JavaScript? Javascript is a single threaded, asynchronous, interpreted language. Various engines of JS runtime are used by different types of browsers to run Javascript code on them, for eg:
V8 for Chrome
SpiderMonkey for Firefox
Chakra for Internet Explorer
All these engines may differ in form or feel, but they have one thing in common, the core functionalities of JS runtime.
How Javascript code is executed?
The JavaScript engine creates an environment known as Execution Context, which manages the complete code transformation and execution process, when it reads a file.
It parses the source code and allocates memory for the variables and functions during the context runtime. After being generated, the source code is run.
There are two kinds of contexts for execution:
- Function
- Global
The global scope in JavaScript is represented by the global execution context, which is created when a script first launches. Every time a function is called, a function execution context reflecting the function's local scope is established.
The execution context for JavaScript is divided into two phases:
Creation Phase: During this stage, the JavaScript engine configures the script's environment and establishes the execution context. It establishes the scope chain for the execution context and establishes the values of variables and functions. In this phase the variables are declared but not initialized so they are undefined during the duration. At then end of creation phase we move to,
Execution Phase: During this stage, the code is run in the execution context by the JavaScript engine. It evaluates any function calls and executes any statements or expressions in the script. During this phase the variables are assigned values provided in the code as we go top to bottom reading each individual line of code.
The Event Loop
image: https://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html
The JS runtime has various parts inside of it, for eg.
Call Stack
Event Loop
Web APIs
Task Queue
let arr=[1,2,3,4,5]
function fun(arr){
arr.forEach((element) =>{
console.log(element);
});
}
fun(arr);
When the above code is executed
First the engine evaluates the script. It identifies keywords, variables, identifiers etc.
The function fun is pushed to the Call stack, where it stays till its execution is complete.
The first console.log statement is executed, which returns the output " 1 "
Similarely the next iterations of the forEach loops are completed which return the output " 2 "," 3 "," 4 "," 5 ".
Only then is the call stack emptied by executing the fun function.
Let us take another example:
function tenth() { }
function ninth() { tenth() }
function eigth() { ninth() }
function seventh() { eigth() }
function sixth() { seventh() }
function fifth() { sixth() }
function fourth() { fifth() }
function third() { fourth() }
function second() { third() }
function first() { second() }
first();
As explained above, the code will run in a similar manner. Here is how the call stack will look by the time the tenth function is called:
As you can see, its filled to the brim, thus while the call stack is being utilised here, other functionalities will not be responsive if I were to run the same code on my website, for eg, a button places will not be responsive unless and until this call stack is empty again after executing all the ten functions.
There are various other methods of making code Asynchronous in Javascript, such as :
Callback Functions
Promises
Async/Await
Thus, we use asynchronous functions, which send the asynchronous tasks to the Task Queue, or Web APIs. there are various asynchronous function in Javascript, which does not in turn block the Call Stack allowing other code snippets to be executing while it is being executed in the background, this is called "Non-blocking Code". For eg.
setTimeout(function a() {}, 1000);
setTimeout(function b() {}, 500);
setTimeout(function c() {}, 0);
function d() {}
d();
When this code is run, function a,b and c will all go to the task queue or the Web APIs whereas function d will be executed in the Call stack, and once that is done executing, the Call stack will be empty, thus signalling the Task queue to push a completed execution snippet to the Call stack, and this process continues until the Task queue and Call stack are empty.
Thus this whole loop of, Call Stack -> Web APIs -> Task Queue , is called the Event loop.
What is Callback?
Callback functions in Javascript are functions that are passed as argument to another function. Callback functions are often used when handling asynchronous functions.
For eg.
function getData(callback) {
setTimeout(() => {
const data = 'Hello World';
callback(data);
}, 1000);
}
function processGetData(data) {
console.log('Data received:', data);
}
getData(processGetData);
Here, the "processGetData" function is being used as a callback function in "getData" function. when getData function is run, callback function for it is also run and the value stored in data variable is passed over as an argument to it.
Callbacks are used in JavaScript for various purposes such as writing asynchronous and event-driven code in Javascript.
What are web browser APIs?
Browser APIs are integrated into our browsers and allow us to process data by accessing it from both the browser and the external environment. One way to work with Document Object Models is through the DOM API. The real job is actually being done by the browser in the background using some complex lower-level code (like C++). But the API conceals these complexities from you. Here are some other web browser APIs:
XHR (XMLHttpRequest) API
Fetch API
Web Storage API
Conclusion
JavaScript is one of the most used languages on the planet, there is always a lot to learn in it, with this article we gathered knowledge about some deeper concepts like callbacks, and event loops in JavaScript which are usually hidden from plain sight.
Resources
About Event Loop : https://www.youtube.com/watch?v=8aGhZQkoFbQ
About JavaScript : https://developer.mozilla.org/en-US/docs/Web/JavaScript
About JavaScript : https://javascript.info/