- A place where it can write and store information such as variables, objects, etc.
- To keep track of where is our code execution is or in simple words, it keeps track of what happens line by line in our code execution.
So, here comes the game of Memory Heap and Call Stack.
Taa daaaa, Blog is done. Everything is over and I think you understood what you need to tell in an interview.
I am just kidding. Let’s dive deep and understand both of the concepts in detail.
Memory heap is a large region in memory that the JS engine uses to allocate memory to the variable, objects, etc that used in the program.
The above code says that please allocate memory for the number variable and point to the value 1 in our memory heap.
The same goes for the string variable, it says that please allocate memory for the string variable and point to the value “hello world” in our memory heap.
Now, I think we are done with Memory Heap, we can jump to Call Stack
Call Stack is a region on the memory that works in last in first out mode. A real-time example will be a stack of stones as shown in the above picture and if you need to add more stones we have to add them at the top to increase the height of the stack and if you want to remove them, we have to remove it from the top. so it works as last in first out principle.
Now let jump into some examples to understand this -
It's a simple program doing some calculations. so here, when we call calculate function the js engine pushes calculate to the call stack. Js engines execute the code line by line and when it encounters minusTwo function, it pushes mintusTwo on top of callstack and after complete execution of minusTwo function call stack returns to calculate function, do the execution of code and we get our result 4 in console
I know it may sound confusing as code is never good to explain by writing, let me attach some screenshots for your reference
In the above attachment, you can observe the whole process, how JS engine is doing the code execution line by line and pushing function to call stack one by one and after executing one function it is poping off from call stack. It’s a awesome thing what can JS engine do to track our code execution.
In the above attachments, you can see the two functions going to the call stack one by one and one and popping out from it after execution of the code.
Simple variables can be stored on the Call Stack and complex data structures such as arrays objects etc are stored in the Memory Heap.
In short, the story is
I tried my best to explain but if you still have any doubts you can connect me through LinkedIn.
Thank you for your time and have a nice day