In JavaScript, stack and heap are two types of memory used for managing data, each with a distinct purpose:
- Stack
- Heap
*What are Stack and Heap *
Stack : The Stack is used for static memory allocation, primarily for storing primitive types and function calls. It's a simple, last-in, first-out (LIFO) structure, making it very fast to access.
Heap : The Heap is used for dynamic memory allocation, where objects and arrays (non-primitive types) are stored. Unlike the Stack, the Heap is more complex and slower to access, as it allows for flexible memory allocation.
Example of Stack Memory :
let myName = "Amardeep"; //primitive type stored in stack
let nickname = myName; // A copy of the value is created in the Stack
nickname = "Rishu"; // Now changing the copy does not affect the original value .
console.log(myName); // output => Amardeep (Original values remains unchanged since we are using stack)
console.log(nickname); // output => rishu (only the copied value will changed)
In this example :
- myName is stored in the Stack as a primitive type.
- When nickname is assigned the value of myName , a copy of that value is created in the Stack .
- Changing nickname doesn't affect myName , since they are independent copies in the memory.
Example of Heap Memory
Now lets check how non-primitive data types(objects) are managed in the Heap .
let userOne = { // The reference to this object is stored in the Stack.
email: "user@google.com",
upi: "user@ybl"
}; // The actual object data is stored in the Heap.
let userTwo = userOne; // userTwo references the same object in the Heap.
userTwo.email = "amar@google.com"; // Modifying userTwo also affects userOne.
console.log(userOne.email); // Output: amar@google.com
console.log(userTwo.email); // Output: amar@google.com
In this example:
- userOne holds a reference to an object stored in the Heap. -userTwo is assigned the same reference, meaning both userOne and userTwo point to the same object in the Heap. -Changing userTwo.email directly affects userOne.email, because both references point to the same location in memory.
Key Takeaways
*Stack Memory * is used for storing primitive types and function calls . Each time you assign a value , a new copy is created in the Stack.
*Heap Memory * is used for storing objects and arrays . Variables that reference the same object share the same memory location in memory , so changing one variable affects the others .
Top comments (0)