The main goal of this article is to help to readers to understand how memory management system performs in JavaScript.

I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.

Image for post

The JavaScript Engine’s Garbage collector’ looks out for objects which are unreachable and also removed from the memory.

So I will share an example below and show you steps that will be needed to work with GC.

var number = 50;                // allocates memory for a number

var string = 'textual data';  // allocates memory for a string
var object = {x: 10};         // allocates memory for an object
var x= [10, null, 'abra'];     // allocates memory for the array
function f(x) {               // allocates memory for a function
return x * 2;
}                              

The example shows how JavaScript allocates memory for the variables when they declare. But when the memory is no longer needed, the allocated memory will be released. GC finds the memory no longer used by the application and releases it. But the main question is that how GC finds the memory no longer used?

The basic algorithm for doing that is called “mark-and-sweep”.

#javascript-development #javascript-tips #javascript-frameworks #javascript #programming

JavaScript Memory Management System
5.10 GEEK