Stack and heap in javascript
Understanding the concepts of stack and heap memory is crucial for mastering JavaScript's memory management.
Table of contents
In JavaScript, memory management involves two main components: the stack and the heap.
1) Stack Memory
Stack memory is primarily used for storing primitive data types. When a variable is declared and stored in the stack, it means that a copy of the variable's value is stored. The actual memory remains unaffected by subsequent changes to the variable.
let name = "React";
let anotherName = name;
anotherName = "JavaScript";
console.log(name); // Outputs: React
console.log(anotherName); // Outputs: JavaScript
hence, we made changes inside the variable which is holding the copy of that variable instead of actual value.
In the example above, anotherName
initially receives the value of name
, which is "React". However, when we assign a new value ("JavaScript") to anotherName
, only the copy stored in anotherName
is changed, while the original value stored in name
remains unaffected.
2) Heap Memory
Heap memory, on the other hand, is used for storing non-primitive data types. When a variable is declared or defined in the heap, it gives a reference to the original value. This means that changes made to the variable affect the original value stored in the heap.
or we can say all the non primitive type is stored inside heap and when you take reference from heap, you get the actual value/or reference of the actual value, instead of copy of that value.
let userOne = {
email: "user@google.com",
upi: "user@ybl"
};
let userTwo = userOne;
userTwo.email = "harsh@google.com";
console.log(userOne.email); // Outputs: harsh@google.com
console.log(userTwo.email); // Outputs: harsh@google.com
In this example, userTwo
receives a reference to the original object stored in userOne
. Therefore, when we update the email
property of userTwo
, the change is reflected in userOne
as well.
Understanding the distinction between stack and heap memory is essential for writing efficient and bug-free JavaScript code. By being mindful of memory management, developers can optimize their code and avoid common pitfalls associated with memory allocation and manipulation.