DEV Community

Cover image for Functions in Memory (Stack)
Khushal Bhardwaj
Khushal Bhardwaj

Posted on

4

Functions in Memory (Stack)

Checkout my twitter thread explaining how functions work in memory (stack).

Things to keep in mind to understand functions behavior

  • When a function is called, it gets in the stack, and stays there until its execution.
  • When the function completes executions, it gets off the stack and returns to the program flow.

Here's a program with a main function that call some other functions and that function call some other function. As they get called, they are loaded into the memory stack.
initial stack

When the function, completes execution the functions gets off the stack and the program returns to the previous program flow, aka to the previous function that called that function.
function getting off the stack
program flow

When there is nothing left in the stack, even the main function that is loaded by default, gets off the stack, the program finishes execution.
empty stack

Takeaways

  • When the function is called, it is loaded on the stack with its arguments.
  • When it completes execution, it gets off the stack and the program returns to its previous program flow.

If "A" function calls "B" function, "A" function will remain in the stack (and in scope also) until the "B" function returns. It means that not only the currently executing function remains in the function but also all the parent function that called it.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay