Memory Management and Garbage Collection in JavaScript

Memory Allocation in JavaScript

This tutorial moves around slightly unfamiliar topic.In JavaScript that is Memory Management and Garbage Collection which is generally ignored by Javascript Developers.After reading this post you will familiar with know-how Memory Management and Garbage Collection is handled in javascript.

In the low-level languages like C, developers need to manually allocate and deallocate the memory using the malloc(), calloc(), realloc(), and free() methods. In the high-level languages like Java and JavaScript, we don’t need to explicitly allocate or release memory. JavaScript values are allocated when things are created (objects, Strings, etc.) and freed automatically when they are no longer used. This process is called Garbage collection.

Memory life cycle

In all high-level programming language Memory life cycle is similar

Allocate the memory you need =>Use the allocated memory (read, write)=>Release the allocated memory when it is not needed anymore

Allocation of Memory in Javascript

Javascript does the Allocation of Memory automatically while declaring the variable.

var num = 105; // allocates memory for a number
var str = 'mastering js'; // allocates memory for a string 
var address = {city: 'new delhi',pincode:110072};  //allocates memory for an object and contained values
var myArray = [3, null, 'Ajay']; //allocates memory for the array

function foo(a) {
  return a + 2;
} // allocates memory for a function 

someElement.addEventListener('click', function() { 'red';
}, false); // function expressions also allocate an object

Read Full post

Also Read

Basic JavaScript interview questions


Please enter your comment!
Please enter your name here