In JavaScript, when we create a variable, function or anything you can think of, the JS engine allocates memory for this and releases it once it’s not needed anymore.
Every time we assign a variable or create a function, the memory for that always goes through the same following stages:

Heap and Stack
JavaScript engines have two places where they can store data: The memory heap and stack.
Stack
- Purpose: Store function calls and their associated data during program execution.
- machanism:
- When a function is invoked, its context (including variable, arguments and return address) is pushed onto the stack.
- The function executes until it returns a value or encounters an exception.
- One function finishes, it context is popped off the stack.
- Behavior:
- Follows the Last-In-First-out(LIFO) principle, meaning the last function called is first one to return
- Overfows can accurr if too many functions are called recursively without returning, leading to stack overflow errors

Heap
The heap is a different space for storing data where JavaScript stores objects and functions.
Unlike the stack, the engine doesn’t allocate a fixed amount of memory for these objects. Instead, more space will be allocated as needed.
Allocating memory this way is also called dynamic memory allocation.
- Mechanism:
- Objects are allocated dynamically in the heap when they are created.
- Each object has a unique reference in memory.
- Garbage collection is responsible for freeing memory occupied by objects that are no longer accessible.
- Behavior:
- Objects can be accessed from anywhere in the code using their references.
- The heap can be fragmented due to frequent object creation and deletion, potentially leading to performance issues.
Relationship Between Call Stack and Heap Memory:
- Function Calls and Object Creation: When a function is called, it may create objects and store references to them on the stack.
- Object Access: Functions can access objects stored in the heap using their references.
- Garbage Collection: When a function returns, any objects it created that are no longer referenced are eligible for garbage collection.

Let’s have a look at the following example. The lines represent references.