JS/TS
  • JavaScript Development
  • JS Principles
    • JS Principles
      • Primitive data types
      • typeof operator
      • Scope
      • Hoisting
      • IIFE
      • Closure
      • Anonymous functions in JS
      • Conditional (ternary) operator
        • Coercion vs Conversion
      • Event-driven programming
      • Factory Function
      • JSON.stringify()
      • Strict mode
      • super() keyword
      • What are memory leaks?
      • Micro-tasks within an event loop (Summary)
      • Macro-tasks within an event loop (Summary)
      • null vs undefined
    • Memory Management
    • Advanced function concepts
      • Impure vs Pure Functions
      • Factory functions
  • JavaScript Objects & Arrays
    • Introducing JavaScript objects
      • Build-in objects
        • isNaN()
      • RegExp
        • RegExp.prototype.test()
      • String
        • String.prototype.split()
        • String.prototype.slice()
      • Objects
        • Object.assign()
        • Object.create()
        • Object.defineProperties()
        • Object.defineProperty()
        • Object.entries()
        • Object.freeze()
        • Object.getOwnPropertyNames()
        • Object.getPrototypeOf()
        • Object.isFrozen()
        • Object.isSealed()
        • Map
      • Standard built-in methods to work with Arrays
        • Array.of()
        • Array.prototype.concat()
        • Array.prototype.every()
        • Array.prototype.filter()
        • Array.prototype.find()
        • Array.prototype.findIndex()
        • Array.prototype.forEach()
        • Array.prototype.join()
        • Array.prototype.map()
        • Array.prototype.pop()
        • Array.prototype.shift()
        • Array.prototype.reverse()
        • Array.prototype.some()
        • Array.prototype.sort()
        • Array.prototype.splice()
        • Array.prototype.unshift()
        • Array.prototype.includes()
        • Array.prototype.flatMap()
      • Prototypal inheritance
        • Inheritance with the prototype chain
        • Inheriting "methods"
  • JavaScript Mid
    • JavaScript & ES
      • Arrow Function
      • Anonymous Function
      • Callbacks
      • Promises
      • var, let, and const
      • Fetch API (function)
      • Fetch API
      • Synchronous vs Asynchronous
      • Encapsulation
      • Destructuring assignment
      • call() - apply() - bind()
      • 'This' keyword
      • Functional Programming
  • Browser
    • Event-driven programming
  • TypeScript
    • The TypeScript Handbook
      • Basic Types
      • Interfaces
      • Functions
      • Literal Types
      • Unions and Intersection Types
      • Classes
      • Enums
      • Generics
      • Implements vs extends
  • Hackerrank Practices
    • Practices and examples
  • JS Math
    • Mathematical
      • JavaScript | Math.E() function
      • Math.abs( ) Method
      • Math.ceil( ) function
      • Math floor()
      • Math.imul( ) Function
      • Math log( ) Method
      • Math max()/min() Method
      • Math pow( ) Method
      • Math.sign( ) Function
      • Math sqrt( ) Method
Powered by GitBook
On this page
  • Memory life cycle
  • Allocation in JavaScript
  • Release when the memory is not needed anymore (What is garbage collector)
  • Garbage collection
  • Limitation: Circular references
  • Real-life example

Was this helpful?

  1. JS Principles

Memory Management

Memory life cycle

Regardless of the programming language, the memory life cycle is pretty much always the same:

  1. Allocate the memory you need

  2. Use the allocated memory (read, write)

  3. Release the allocated memory when it is not needed anymore

The second part is explicit in all languages. The first and last parts are explicit in low-level languages but are mostly implicit in high-level languages like JavaScript.

Allocation in JavaScript

Value initialization

In order to not bother the programmer with allocations, JavaScript will automatically allocate memory when values are initially declared.

var n = 123; // allocates memory for a number
var s = 'azerty'; // allocates memory for a string

var o = {
  a: 1,
  b: null
}; // allocates memory for an object and contained values

// (like object) allocates memory for the array and
// contained values
var a = [1, null, 'abra'];

function f(a) {
  return a + 2;
} // allocates a function (which is a callable object)

// function expressions also allocate an object
someElement.addEventListener('click', function() {
  someElement.style.backgroundColor = 'blue';
}, false);

Release when the memory is not needed anymore (What is garbage collector)

Garbage collection

As stated above, the general problem of automatically finding whether some memory "is not needed anymore" is undecidable. As a consequence, garbage collectors implement a restriction of a solution to the general problem. This section will explain the concepts that are necessary for understanding the main garbage collection algorithms and their respective limitations.

Limitation: Circular references

There is a limitation when it comes to circular references. In the following example, two objects are created with properties that reference one another, thus creating a cycle. They will go out of scope after the function call has completed. At that point they become unneeded and their allocated memory should be reclaimed. However, the reference-counting algorithm will not consider them reclaimable since each of the two objects has at least one reference pointing to them, resulting in neither of them being marked for garbage collection. Circular references are a common cause of memory leaks.

function f() {
  var x = {};
  var y = {};
  x.a = y;        // x references y
  y.a = x;        // y references x

  return 'azerty';
}

f();

Real-life example

Internet Explorer 6 and 7 are known to have reference-counting garbage collectors for DOM objects. Cycles are a common mistake that can generate memory leaks:

var div;
window.onload = function() {
  div = document.getElementById('myDivElement');
  div.circularReference = div;
  div.lotsOfData = new Array(10000).join('*');
};

In the above example, the DOM element "myDivElement" has a circular reference to itself in the "circularReference" property. If the property is not explicitly removed or nulled, a reference-counting garbage collector will always have at least one reference intact and will keep the DOM element in memory even if it was removed from the DOM tree. If the DOM element holds a large amount of data (illustrated in the above example with the "lotsOfData" property), the memory consumed by this data will never be released and can lead to memory related issues such as the browser becoming increasingly slower.

Previousnull vs undefinedNextAdvanced function concepts

Last updated 4 years ago

Was this helpful?

Some high-level languages, such as JavaScript, utilize a form of automatic memory management known as (GC). The purpose of a garbage collector is to monitor memory allocation and determine when a block of allocated memory is no longer needed and reclaim it. This automatic process is an approximation since the general problem of determining whether or not a specific piece of memory is still needed is .

The garbage collector, or just collector, attempts to reclaim , or memory occupied by that are no longer in use by the . Garbage

garbage collection
undecidable
garbage
objects
program