Article

Call Stack: Administering function calls

This is in continuation to JavaScript runtime: Call Stack and Event Queue - Part 1

var first = function() {
    console.log("Hello One");
};
var second = function () {
    first();
    console.log("Hello Two");
};
second();

Call Stack: Administering function calls

The Call Stack and the Event Queue are the two main components of the JavaScript runtime that are responsible for managing the execution of the JavaScript code. The job of the call stack is to manage the function calls. One of JavaScript's strengths is how it handles asynchronous code (callbacks). Instead of blocking the thread, this code is pushed to an event queue that fires after all other code executes. Let us first discuss the call stack in detail.

A call stack is composed of one or many several stack frames. When a function is called, a new stack frame is created corresponding to the function invoked. This stack frame holds the pointer to the function that itself is stored in the heap memory. In addition, the arguments to the function, its local variables, and the return value are also stored in the frame. In other words, each stack frame represents a call to a function which has not yet terminated with a return including the frame of data that gets pushed onto the stack. At function return, its frame is popped off from the stack. Since the call stack is organized as a stack data structure, a function invoking another function will result in pushing another frame on the top of the call stack, and so on, with the information stacking up and unstacking as the program dictates.

Note that for the sake of simplicity, the fact that the console.log calls are also pushed onto the call stack has been deliberately omitted.

For Part 3, click this link: JavaScript runtime: Call Stack and Event Queue - Part 3