What is happening under the hood ?
The JavaScript engine, is a single-threaded interpreter comprising of a single call stack, heap, messages queue and event loop. The browser provides web APIs like the DOM, AJAX, and Timers.
Call Stack
At the most basic level, a call stack is a data structure that uses the Last In, First Out (LIFO) principle to temporarily store and manage function invocation (call) . If we call a function to execute , we push something on to the stack, and when we return from a function, we pop off the top of the stack.
The call stack is primarily used for function invocation (call). Since the call stack is single, function(s) execution, is done, one at a time, from top to bottom. It means the call stack is synchronous.
One item of call stack is called stack frame, for example invocation of one function.
Call Stack example (credits)
function functionOne(){
functionTwo();
}
function functionTwo(){
functionTree();
}
function functionTree(){
throw new Error('This is error');
}
functionOne();
Executing this code we will receive current call stack as console error.
Everybody knows "stack overflow" but what it means ? It happens when call stack maximum size ( depending on browser ) has been exceeded.
function computeMaxCallStackSize() {
try {
return 1 + computeMaxCallStackSize();
} catch (e) {
// Call stack overflow
return 1;
}
}
console.log(computeMaxCallStackSize());
Checking of max call stack size (credits)
Heap
Objects are allocated in a heap which is just a name to denote a large mostly unstructured region of memory.
Messages (callback) queue
Message queue is a list of messages to be processed. To each message is associated a function. When the stack is empty, a message is taken out of the queue and processed. The processing consists of calling the associated function (and thus creating an initial stack frame). The message processing ends when the stack becomes empty again.
Event loop
It is mechanism which:
- check if call stack is empty
- get first message from queue
- process message calling associated function
How it works together ?
JavaScript runtime representation (credits)
- Init user function is invoked, where are defined button click listeners, timers etc
- Event is triggered ( eg. button click )
- Web Api add message to queue
- Event loop process message
Resources
https://developer.mozilla.org/pl/docs/Web/JavaScript/EventLoop
https://medium.freecodecamp.org/understanding-the-javascript-call-stack-861e41ae61d4