JavaScript Call Stack

JavaScript Call Stack

In this article, we will talk about JavaScript, there are some concepts related to each other in JavaScript.

Call stack - web API - Event loop - callback Queue.

First, we will talk about call stack we use it for tracking the code in order to know what runs first in our code after that when we call a function it's added to our 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.

The understanding of the call stack is vital to Asynchronous programming (which we will look at in a later article).

In Asynchronous JavaScript, we have a callback function, an event loop, and a task queue. The callback function is acted upon by the call stack during execution after the call-back function has been pushed to the stack by the event loop.


LIFO: When we say that the call stack, operates by the data structure principle of Last In, First Out, it means that the last function that gets pushed into the stack is the first to pop out when the function returns.

example

console.log("welcome") //1
console.log("hello") // 2
console.log("thx") // 3 ,


In the above example, the order of output will be normal and in the same order you see, but we have to be careful because there are some methods related to Web API and this method call stack makes it detect because this method is implemented by browser and of the methods related to Web API like setTimeout(), setInterval()

example.


console.log("one") 
window.setTimeout( ( ) => console.log("two") , 0) 
console.log("three")


If you see this example without paying attention, you'll say it's the same as the first example above but different in this example. The output will be (one, three, two) because setTimeout() is from the web API and is executed by the browser and because the methods related to the web API, the first time the execution finishes and returns its callback, it is added to the callback queue, here The event loop comes into play because it checks all the needs in the call stack. Finished or not finished yet, after making sure that it is finished, it will go to the callback queue to add them to the call stack and execute them.


If you find article useful or you want to discuss it with me you can send it to me on Twitter Twitter