When an object on the heap has no references pointing to it, it becomes unreachable. The garbage collector uses mark-and-sweep to identify and free such objects.
How JavaScript Allocates Memory for Variables and Functions
When does the garbage collector free memory in JavaScript?
The answer
More FAQs in How JavaScript Allocates Memory for Variables and Functions
Objects, arrays, and functions are stored on the heap. The variable holds a reference (pointer) to that heap location, which is why copying a variable shares the same object.
Primitives like number, string, and boolean are stored directly where the variable lives, typically on the call stack. They copy by value on assignment.
Primitives copy by value, so changes to one variable do not affect the other. Objects copy by reference, so two variables can point to the same object and mutations are visible through both.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.