Javascript Call Stack and Memory Heap

Javascript Call Stack and Memory Heap

This is a brief overview of how the Javascript engine uses the call stack and memory heap to keep a hold of the execution context. The engine needs to track where we are in the code (call stack) and somewhere to store and remove values (memory heap)

  • Memory heap

    • Unordered free space allocated in memory.
  • Call stack

    • A region in memory that keeps track of function calls and operates in “first in last out” mode. Functions tracked in the call stack, point to the memory heap to get the values they need to complete their tasks.

Simple variables are stored on the call stack itself, but more complex data structures like objects and functions are stored on the memory heap.

Javascript is a garbage-collected language. When javascript finishes up an operation, it automatically cleans up the memory heap to free up space. So do we need to care about memory management? Yes. We still need to be careful to allow the garbage collector to clean up memory.

How does garbage collection work in Javascript? It uses the “mark and sweep” algorithm. Basically, anything that points references something in memory is kept otherwise it’s deleted. The image below gives a shows a basic implementation of this algorithm:

mark and sweep

Memory leaks happen when a piece of memory that is no longer needed is not cleaned up by the garbage collector.

Examples of memory leaks:

  • Declaring global variables
  • Adding, but not removing event listeners
  • Using setInterval without clearing it