theory.js

JavaScript Memory Management

How Garbage Collection Works

JavaScript automatically manages memory using garbage collection, freeing up memory occupied by unreachable objects.

  • Garbage collection removes objects that are no longer referenced.
  • JavaScript uses the mark-and-sweep algorithm to identify unused objects.
  • Variables inside functions are cleared after execution unless referenced elsewhere.
function example() {
  let temp = { name: "Jake" }; // Object is created
  console.log(temp.name); // "Jake"
} // After this function runs, 'temp' is unreachable and garbage collected