<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Ankit parte</title>
    <description>The latest articles on Forem by Ankit parte (@ankitparte80).</description>
    <link>https://forem.com/ankitparte80</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F956872%2F4b482a70-88fe-4825-b7b7-2ae687078446.jpg</url>
      <title>Forem: Ankit parte</title>
      <link>https://forem.com/ankitparte80</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/ankitparte80"/>
    <language>en</language>
    <item>
      <title>JS Memory Management</title>
      <dc:creator>Ankit parte</dc:creator>
      <pubDate>Sun, 06 Oct 2024 11:01:00 +0000</pubDate>
      <link>https://forem.com/ankitparte80/js-memory-management-3h51</link>
      <guid>https://forem.com/ankitparte80/js-memory-management-3h51</guid>
      <description>&lt;p&gt;Memory management is a crucial aspect in every kind of coding language which ensures efficient use of memory during code execution.&lt;/p&gt;

&lt;p&gt;So understanding how Javascript manages memory can help us write more optimised, performant and scalable application. Memory management issues such as inefficient use of memory and memory leaks can lead to poor application performance, slowdowns and even crashes.&lt;/p&gt;

&lt;p&gt;In this article I want to cover about how Javascript handles memory, memory allocation, garbage collection and common memory pitfalls and strategies for efficient memory usage.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. What is Memory management
&lt;/h3&gt;

&lt;p&gt;Memory management in programming involves controlling how memory is allocated and freed as program runs. Javascript, like many high-level languages, uses &lt;strong&gt;automatic memory management&lt;/strong&gt; through a process called &lt;strong&gt;Garbage Collection&lt;/strong&gt;. This relieves developer from explicitly managing memory but requires an understanding of how memory is allocated and freed to prevent issue like memory leaks and excessive memory consumption.&lt;/p&gt;

&lt;h5&gt;
  
  
  Memory Life Cycle
&lt;/h5&gt;

&lt;ol&gt;
&lt;li&gt;Memory Allocation - The process of reserving memory for variables, objects and functions.&lt;/li&gt;
&lt;li&gt;Memory Usage - Actively using the allocated memory (e.g., reading or writing to a variable, calling a function).&lt;/li&gt;
&lt;li&gt;Memory Release - Once the memory is no longer needed, it should be released back to the system (in JavaScript, this is done by garbage collection).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  2. Memory allocation in Javascript
&lt;/h3&gt;

&lt;p&gt;Javascript automatically allocates memory when variables are declared or when objects and when function are created.&lt;/p&gt;

&lt;h5&gt;
  
  
  For Primitive Values
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 1;    // Allocates memory for the number 1
let name = 'Baki';  // Allocates memory for the string 'Baki'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we declare a primitive, Js allocates memory for the value and stores it directly in the variable. Primitive type data directly stored in the stack and have a fixed size.&lt;/p&gt;

&lt;h5&gt;
  
  
  For Non-Primitive Values
&lt;/h5&gt;

&lt;p&gt;When we create an object, array or functions they all are stored in &lt;strong&gt;heap&lt;/strong&gt; and the variables contains a reference(or pointer) to the memory location in the &lt;strong&gt;heap&lt;/strong&gt;. These types do not have fixed size and can grow dynamically.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let person = { name: 'Baki', age: 20 };  // Allocates memory for the object in the heap
let numbers = [1, 2, 3, 4];  // Allocates memory for the array in the heap
function Greet() {
  console.log('Hello, World!');
}
//Functions are first class object in Js, which means they are treated as objects and also stored in the heap.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. Garbage collection
&lt;/h3&gt;

&lt;p&gt;Js automatically frees memory that is no longer in use through a process known as Garbage Collection. The most common algorithm used by Js engines for garbage collection is the Mark and Sweep algorithm.&lt;/p&gt;

&lt;h5&gt;
  
  
  Mark-and-Sweep Algorithm
&lt;/h5&gt;

&lt;p&gt;It works as follows&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Marking Phase - The garbage collectors marks all the variables and objects that are reachable(i.e., accessible from the &lt;strong&gt;root&lt;/strong&gt;, such as global variables, the current function call stack, and event listeners). These are considered alive.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Sweeping Phase - It then checks for variables and objects that are not reachable(i.e., no references to them exist). These objects are considered garbaged and are removed, and memory is released.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Example
let user = { name: 'Jack' }; // user references an object
user = null;  // user no longer references the object, so the object becomes unreachable and memory is freed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In above example, the object &lt;code&gt;{ name : 'Jack' }&lt;/code&gt; is no longer referenced when &lt;code&gt;user&lt;/code&gt; is set to null. The garbage collector will eventually free up memory for unreachable object.&lt;/p&gt;

&lt;h5&gt;
  
  
  Root reference
&lt;/h5&gt;

&lt;p&gt;The root of the memory graph is typically the global object(&lt;code&gt;window&lt;/code&gt; in browser or &lt;code&gt;global&lt;/code&gt; in Node.js). All variables, objects and functions that are reachable from the root are considered 'alive' and will not be garbage-collected.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Memory leaks
&lt;/h3&gt;

&lt;p&gt;A memory leak occur when memory that is not longer in use is not released. This can cause your application to consume more and more memory over time, leading to degraded performance and even crashes. Memory leaks are usually caused by unreachable objects that the garbage collector cannot remove because they are still referenced in some part of the code.&lt;/p&gt;

&lt;p&gt;Below is the list of common memory leak issues.&lt;/p&gt;

&lt;h5&gt;
  
  
  1. Unintentional Global Variables
&lt;/h5&gt;

&lt;p&gt;Declaring variables without &lt;code&gt;var&lt;/code&gt;, &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; creates implicit global variables, which stays in memory for the lifetime of the page and are not garbage-collected.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function setUser() {
  name = 'Jack';  // Implicit global variable
}
setUser();
// 'name' is now a global variable and will never be garbage-collected

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  2. Closures
&lt;/h5&gt;

&lt;p&gt;While closures are useful features, But without intention they can cause memory leaks if not managed properly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function outer() {
  let bigObject = { name: 'Huge object' };
  return function inner() {
    console.log(bigObject);
  };
}

const closure = outer();  // 'bigObject' remains in memory due to closure

// to release memory, assign such variables value to null after use
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, the &lt;code&gt;inner&lt;/code&gt; function creates a closure that holds onto the reference to &lt;code&gt;bigObject&lt;/code&gt;. Even though &lt;code&gt;outer()&lt;/code&gt; has returned, &lt;code&gt;bigObject&lt;/code&gt; cannot be garbage collected as long as the closure exists.&lt;/p&gt;

&lt;h5&gt;
  
  
  3. DOM References
&lt;/h5&gt;

&lt;p&gt;Sometimes, memory leaks occurs when Js retains references to DOM elements that have been removed from the document. This can prevent the DOM elements from being garbage-collected.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let button = document.getElementById('myButton');
button.addEventListener('click', function handleClick() {
  console.log('Button clicked');
});
// Later, the button is removed from the DOM
document.body.removeChild(button);  // Button still in memory due to event listener

//solution, remove event listeners when they are no longer used
button.removeEventListener('click', handleClick)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  4.Timers(setInterval and setTimers)
&lt;/h5&gt;

&lt;p&gt;Timers like &lt;code&gt;setTimer&lt;/code&gt; and &lt;code&gt;setInterval&lt;/code&gt; can cause memory leaks if not properly cleared.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let counter = 0;
const intervalId = setInterval(() =&amp;gt; {
  console.log(counter++);
}, 1000);

// Later, if clearInterval() is not called, this will keep running indefinitely

//solution, always use clearTimer() or clearInterval() when timers no longer needed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;Memory management in Js is largely automatic thanks to garbage collection. But understanding how memory allocation and deallocation works is critical for writing efficient and optimised code. As a Good Engineer, your ability to detect and prevent memory leaks, manage closures, handle DOM reference and optimise memory usage in complex applications will have a significant impact on application performance and user experience.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Performance, Efficiency, Maintainability and Scalability matters the most.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Sources of Learning
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;MDN Docs&lt;/li&gt;
&lt;li&gt;Youtube, Internet&lt;/li&gt;
&lt;li&gt;LLM, Chatgpt&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>webdev</category>
      <category>learning</category>
    </item>
  </channel>
</rss>
