JavaScript automatically allocates memory when objects are created and frees it when they aren't used anymore(Garbage Collection).
Memory leak in JavaScript is a part of the memory that no longer, but is still kept by the program and is not released by the Garbage Collector. This makes the program consumption more and more and eventually slows down or even crashing the program.
Allocation in JavaScript
JavaScript will automatically allocate memory when values are initially declared.
- Allocates memory for a number
const num=567;
2.Allocates memory for a string
const text="description";
3.Allocates memory for an object and contained values
const person={
name:"maryam",
age:30
}
4.Allocates memory for the array
const colors=["red","green","blue"];
5.Allocates memory for a function
function sum(a,b){
return a+b;
}
6.Allocates memory for an eventListener
divElement.addEventListener("click",()=>{
divElement.style.backgroundColor="blue";
})
7.Allocates memory for a Date object
const dateNow=new Date();
Reason for Memory Leak
In JavaScript, the Garbage Collector only releases an object when there is no refrence.
If you unintentionally hold the refers to an object, that object will never be released.
1.Global variables unwanted
function foo() {
leakVar = "I am leaked"; // without let/const/var → global
}
foo();
This variable remains in the entire life of the program.
2.References in Closures
function createLeak () {
let Bigdata = New Array (1000000) .fill ("Leak");
return function () {
console.log (Bigdata [0]);
};
}
const leaky = createLeak (); // Bigdata is still holding
Because Closure still refers to Bigdata, memory is not released.
3.Events uninvited Listener
function Attach () {
consting instant = document.getElementById ("BTN");
element.addEventListener ("click", () => console.log ("click!");
// If the element is deleted but the listener is not erased → leak
}
Even after eliminating the Element from the DOM, the memory will not be released if the Listener is not erased.
4.Objects stored in data structures (such as Map/Set) that are not deleted
const cache = new map (); function addCache (Key, Value) {
cache.set (key, value); // If the Keys are not deleted → leak
}
Ways to prevent Memory Leak
1.Limit the Global variables (always use let, const or var).
2.Wipe the Event Listener after use:
element.removeEventListener("click", handler); //Null or delete in time.
3.In data stations like MAP and SET, delete it if data is no longer necessary.
4.For temporary data, use weakmap and weakset that automatically release memory.
Top comments (0)