SoFunction
Updated on 2025-05-13

JavaScript garbage collection and closure examples explain in detail

Garbage recycling

Mark clear

When a variable enters the environment, it is marked as "enter the environment". When a variable leaves the environment, it is marked as "Leave the environment". The garbage collector destroys the marked values ​​and recycles the memory space they occupy.

function test() {
  var a = 1; // When function calls, it is marked and enters the context}
test(); // After the function is executed, the mark of a is removed and recycled

Quote count

When a variable is declared and a reference type value is assigned to the variable, the number of references to this value is 1. If the same value is assigned to another variable, the number of references to the value is increased by 1. On the contrary, if the variable containing the reference to this value takes another value, the number of references to this value is reduced by 1. When the number of references to this value becomes 0, it means that there is no way to access the value again, so the memory space it occupies can be reclaimed. When the garbage collector runs again next time, it frees up memory that values ​​with 0 references.

function test() {
  var a = {}; // The number of references of a is 0, and it is recycled  var b = a; // Add 1 to a reference number to 1  var c = a; //A quotes are added to 1, which is 2  a = 1; // The number of references of a is reduced by 1 to 1  b = 1; // The number of references of a is reduced by 1 to 0, and can be recycled  c = 1; // The number of references of a is reduced by 1 to 0, and can be recycled}

Closure

A closure is a function that has permission to access variables in another function scope. A common way to create closures is to create another function inside one function. Closures allow functions to continue accessing the lexical scope when defined.

Another use of closures is to encapsulate private variables.

function createCounter() {
  let count = 0;
  return {
    increment: function () {
      count++;
    },
    getCount: function () {
      return count;
    },
  };
}

const counter = createCounter();
();
(()); // 1

Disadvantages of closures:

  • Since closures will cause all variables in the function to be stored in memory, and the memory consumption is very large, closures cannot be abused, otherwise it will cause performance problems of the web page and may lead to memory leakage in IE. The solution is to delete all local variables that are not used before exiting the function.
  • The closure changes the value of the variable inside the parent function outside the parent function. Therefore, if you use the parent function as an object, use the closure as its public method, and use the internal variable as its private property, be careful not to change the value of the internal variable of the parent function at will.
  • The disadvantage of closures is that they are resident memory, which will increase memory usage, and improper use can easily lead to memory leakage.

Uses of closures

  • Create private variables
    function createCounter() {
      let count = 0;
      return {
        increment: function () {
          count++;
        },
        getCount: function () {
          return count;
        },
      };
    }
    
  • Simulate block-level scope
    (function () {
      for (var i = 0; i < 10; i++) {
        (i);
      }
    })();
    
  • Implement curriculation
    function add(a, b, c) {
      return a + b + c;
    }
    
    function curry(fn) {
      return function curried(...args) {
        if ( >= ) {
          return (this, args);
        } else {
          return function (...args2) {
            return (this, (args2));
          };
        }
      };
    }
    
    const curriedAdd = curry(add);
    (curriedAdd(1)(2)(3)); // 6
    
  • Implement function throttling and anti-shake
    function throttle(fn, delay) {
      let timer = null;
      return function (...args) {
        if (!timer) {
          timer = setTimeout(() => {
            (this, args);
            timer = null;
          }, delay);
        }
      };
    }
    
    function debounce(fn, delay) {
      let timer = null;
      return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          (this, args);
        }, delay);
      };
    }
    
  • Implement singleton mode
    function Singleton(fn) {
      let instance = null;
      return function (...args) {
        if (!instance) {
          instance = new ((this, ...args))();
        }
        return instance;
      };
    }
    
    function User(name) {
       = name;
    }
    
    const createUser = Singleton(User);
    const user1 = createUser('Alice');
    const user2 = createUser('Bob');
    (user1 === user2); // true
    
  • Implement modular development
    const module = (function () {
      let privateVar = 0;
      function privateFunc() {
        ('privateFunc');
      }
      return {
        publicFunc: function () {
          ('publicFunc');
        },
      };
    })();
    (); // publicFunc
    (); // TypeError:  is not a function

Summarize

This is the end of this article about JavaScript garbage collection and closures. For more related JS garbage collection and closure content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!