Node.js Course
Node.js
/
Advanced

Garbage Collection

Definition

The automatic memory management feature in the V8 engine that reclaims memory occupied by objects that are no longer in use by the program.

Explain Like I'm New

Imagine your computer's RAM is a massive hotel. When you create an object `const user = {}`, the hotel gives you a room. If you forget to check out, the hotel eventually runs out of rooms. The Garbage Collector is the hotel maid. Every few seconds, she knocks on doors. If a room is occupied by data that is no longer being used anywhere in your code, she kicks it out and frees up the room.

Real World Example

If you write a function that calculates a large array, and then the function ends, there are no more references pointing to that array. The V8 Garbage Collector realizes it's 'unreachable' and deletes it from memory.

Common Use Cases

  • •Memory management
  • •Performance tuning

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • Do you need to manually delete objects from memory in JavaScript using a command like `free(obj)`?

intermediate

  • What algorithm does V8 primarily use for Garbage Collection?

Flash Cards

Question

Manual deletion?

Click to reveal answer
Answer

No. Unlike C or C++, JavaScript memory management is completely automated.

Question

What algorithm?

Click to reveal answer
Answer

Mark-and-Sweep. It starts at the global root (the window or process) and traces every single variable that is currently reachable. It 'Marks' them as alive. Then it 'Sweeps' through memory and deletes anything that wasn't marked.