📚 Call Stack in Javascript 🧱

If you have started learning JavaScript and created basic applications such as a to-do app or calculator, you may have wondered how the code you wrote works behind the scenes. How does the computer know when to run a function or initialize it? This is where the call stack comes in. In this article, I will explain what the call stack is and how it works.

Call Stack is a stack data structure that stores information about the active subroutines of a computer program. It is a last-in, first-out (LIFO) data structure, which means that the last function added to the stack is the first one to be removed. When we invoke a function, it gets added to the call stack and when a function returns a value, it gets popped off the stack.

The computer reads the code from top to bottom, and whenever it encounters a function call, it adds that function to the call stack. For example, let’s look at this code snippet:

In this example, we have three functions: myFunc, yourFunc, and summaryFunc. When we invoke summaryFunc in the last line of the code, it is added to the call stack.

Inside summaryFunc , first myFunc is called and added to call stack.

and it logs the message "My name is Suleyman" to the console.

Once the function is finished executing, it is removed from the call stack.

Then yourFunc is executed, which logs the message "Your name is Sultan" to the console.

Once again, the function, yourFuncis removed from the call stack.

Finally, the console.log function is called to log the message "The summary of names: Sultan Suleyman" to the console.

Once summaryFunc is finished executing, it is removed as well.

It’s important to note that functions are added to the call stack in the order that they are called. This means that the last function added is always the first one to be executed and the first one to be removed from the stack.

The call stack is a critical component of the JavaScript runtime environment, and understanding how it works can help you write more efficient. For example, you should be aware of the possibility of stack overflow errors, which can occur when the call stack grows too large due to a large number of nested function calls.

Additionally, you should be mindful of callback hell, which is a common problem that occurs when you nest too many callbacks within each other, leading to code that is difficult to read and maintain.

If you want to learn about the event loop on top of the call stack, you can check out my article:
https://gnwx.hashnode.dev/do-you-know-js-event-loop-skip-read-this-article

Resources:

youtube.com/watch?v=xFNWb7KiG58

freecodecamp.org/news/understanding-the-jav..

developer.mozilla.org/en-US/docs/Glossary/C..

youtube.com/watch?v=iLWTnMzWtj4

Â