JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

What is the difference between stack and heap memory in JavaScript?

Asked on Jul 24, 2024

Answer

In JavaScript, stack and heap memory are used to store different types of data. The stack is used for static memory allocation, storing primitive values and function calls, while the heap is used for dynamic memory allocation, storing objects and functions.
// Example of stack memory usage
        function add(a, b) {
            const sum = a + b; // 'sum' is stored in the stack
            return sum;
        }

        // Example of heap memory usage
        const person = {
            name: "Alice",
            age: 30
        }; // 'person' object is stored in the heap
Additional Comment:
  • Stack memory is fast and automatically managed, ideal for storing primitive data types and function calls.
  • Heap memory is larger and used for objects and functions, allowing for dynamic memory allocation.
  • Stack is limited in size compared to the heap, which can lead to stack overflow if not managed properly.
  • JavaScript's garbage collector automatically reclaims memory from the heap when objects are no longer in use.
✅ Answered with JavaScript best practices.
← Back to All Questions