Heap and memory management in JavaScript
Heap and manage storage JavaScript
Memory management varies significantly between different programming languages. In low-level languages like C or C++, programmers must manage it manually.
On the other hand, in high-level languages like JavaScript, Python, or C#, memory management is automatic. This means that space is allocated dynamically while it is needed and released automatically when it is no longer required, thanks to the process known as Garbage Collection. However, in the latter, problems such as memory leaks can arise, resulting in memory overhead. In this article, we will explore how to address these problems, but first, it is crucial to understand how they work.
To understand how it works, we must first understand the data types used in JavaScript.
Data Types in JavaScript
Primitive Types: These data are stored directly in the stack.
String | Number | Boolean | Null | Undefined | Symbol | Bigint
Reference Types: They are stored in the heap and accessed through references.
Array | Function | Objects
Let's delve into the differences with a concrete example:
let name = "José";
let age = 40;
let person = {
name: "Pablo",
age: 30,
};
let newName = name;
newName = "Lázaro";
let newPerson = person;
newPerson.name = "Jesús";
console.log(name);
console.log(person);
console.log(newName);
console.log(newPerson);
José
{ name: "Jesús", age: 30 }
Lázaro
{ name: "Jesús", age: 30 }
It is worth noting that the primitive variable 'name', with the value "José", retains its original value despite being assigned to 'newName' and being overwritten with "Lázaro". On the other hand, when performing the same operation with the 'person' object, the value of the name changes in both variables. This is because an independent copy is not created; instead, it is accessed via reference.

Memory Leak
One of the most powerful tools for detecting memory leaks in web applications is the set of developer tools integrated into browsers. In particular, DevTools offer specific functionalities to monitor memory usage. To detect a memory leak, we can use the "Memory" tab in DevTools, where we can observe unexpected growth in memory consumption during certain time periods or user actions. For example, if we notice a constant increase in memory usage after loading a page or performing certain interactions, this could indicate a possible memory leak. Furthermore, DevTools usually provide tools for more detailed analysis, such as taking memory profiles and visualizing memory retention by objects and DOM elements. Below is a screenshot of DevTools with an example of a memory leak, where a constant increase in memory usage can be observed after certain actions on the web page.



