Simply and Easily Understanding Function Call Stack by a Vision


Background

I shared content about Javascript event loop and task queue on 1st March to my colleagues. one of these colleagues asked me what is call stack. I give an example by blackboard as my explanation. But I thought I should give an animation to understand how to call stack run. So I start writing this article.


Understanding Stack

As we know, a stack is an abstract data type. The item coming off a stack is LIFO (last in first out). Click the below links to read more about stack.


View Stack by Chrome Devtool

First, you should open the chrome developer tool by keyboard F12 or mouse right-click menus Inspect. You should know how to open developer tool if you are a web developer. Secondly, refresh this page, and you will see this page was stuck because I add a debugger in Javascript code. There is a panel with a red edge. It called call stack. Yes, that's Javascript's engine function call stack.



You could debug it by step over/into/out if you are a front-end developer.


How Function Call Stack Run?

I develop a visual animation tool to help you deeply understand the function call stack. You could click the start button to run the below code. The code’s function is to print my name. It’s simple code but you could extend to understand your code.You could clearly see the below code's function call stack.

function printName() {
   let name = getName();
   console.log(`My Chinese name is ${name}.`);
}
function getName() {
    let firstName = getFirstName();
    console.log('11');
    let lastName = getLastName();
    return `${firstName}${lastName}`;
}
function getFirstName() {
    return 'You';
}
function getLastName() {
    return 'Shaohua';
}
printName();

Call Stack


I have to say that I implement the tool by a stupid and simple method to save my time. I have not to write the simple compiler for this code. haha...


Summary

The function call stack is code execution order. A function will pop from the stack if it completely executed. A function will push if enter the function into the stack. We can know the sync code execution order.

Read More


This article is original, licensed under a Creative Commons Attribution 4.0 International license