In JavaScript, stack and heap are two types of memory used for managing data, each with a distinct purpose:
*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 :
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:
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 .
The above is the detailed content of Understanding Stack and Heap in JavaScript .. For more information, please follow other related articles on the PHP Chinese website!