Suggest an editImprove this articleRefine the answer for “What does the garbage collector (GC) do?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**The garbage collector (GC)** is a mechanism of the JavaScript engine (for example, V8) that automatically frees memory occupied by objects that have become unreachable. **Key point:** GC removes from memory everything that no longer has references, based on the "reachability" principle, not manually like `free()` in C++.Shown above the full answer for quick recall.Answer (EN)Image## 1. What the garbage collector (GC) does > The **garbage collector (Garbage Collector)** is a mechanism of the JavaScript engine (for example, V8), > which **automatically frees memory** occupied by **objects that have become unreachable**. That is, GC removes from memory everything **that no longer has references to it**, so as not to waste resources and to prevent memory overflow. --- ## 2. How it works under the hood The JS engine manages memory like this: 1. It allocates memory for new objects: ```javascript let user = { name: 'Tim' }; // memory allocated ``` 2. If a variable stops referencing an object: ```javascript user = null; // the old reference is lost ``` 3. GC understands that the object `{ name: 'Tim' }` is **unreachable**, and in the nearest cycle it will **free the memory**. --- ## 3. Key concept - "reachability" > In JS, memory is cleaned up **not manually**, but according to the **reachability** principle. **Reachable** objects: - global variables (`window`, `global`, `globalThis`); - local variables on the stack (while a function is running); - objects referenced by other reachable objects. **Unreachable**: - objects that **have no references** from reachable places. **Example:** ```javascript let user = { name: 'Alice' }; let admin = user; // two references to one object user = null; // the object is still reachable through admin admin = null; // now the object is unreachable -> GC will remove it ``` --- ## 4. Example with a chain of references ```javascript function createUser() { const user = { name: 'Bob' }; const address = { city: 'Paris' }; user.addr = address; address.owner = user; // a circular reference! return user; } const person = createUser(); ``` Here the object `user` references `address`, and vice versa. If afterward: ```javascript person = null; ``` -> Both objects **become unreachable** (they can't be reached from the root) -> GC frees both, despite the circular references. JS's GC knows how to detect such cycles. --- ## 5. How it works (using V8 as an example) V8 (the Chrome and Node.js engine) uses the **"mark-and-sweep" algorithm**: 1. **Mark:** GC walks from the "root" objects (root: `window`, `global`, the call stack) and marks everything that is reachable. 2. **Sweep:** Everything **that was not marked** is removed from memory. 3. **Compact:** Sometimes memory is "compacted" to free up space. V8 also has: - **Minor GC (Scavenge)** - for "young" objects (new, short-lived); - **Major GC (Mark-Sweep-Compact)** - for "old" objects (longer-lived, checked less often). --- ## 6. How GC affects performance - GC runs **automatically and asynchronously**, but sometimes causes **small pauses** (GC pauses). - The more "live" objects there are, the longer a GC cycle takes. - Memory leaks interfere with GC - it considers "dangling" references to be live. So: > Optimal code = fewer long-lived objects + timely "breaking" of references. --- ## 7. What GC does **not** do | Doesn't do | Why | |---|---| | Doesn't clean everything at once | So as not to interfere with the program's work | | Doesn't see "logical uselessness" | Only the absence of references - not "intelligence" | | Isn't controlled manually | There's no `free()` / `delete` like in C++ | | Doesn't clean up global objects | They are always reachable via `window` / `globalThis` | --- ## 8. Common mistakes that hinder GC | Mistake | What happens | |---|---| | Global variables | stay reachable forever | | Timers and listeners left uncleaned | references keep closures alive | | DOM references after an element is removed | GC cannot remove it | | Closures holding large objects | "leaks" through the scope | --- ## 9. How to inspect GC and memory **In the browser:** - Chrome DevTools -> the **Memory** tab -> "Heap snapshot" - The **Performance -> Memory** tab -> "Record" - The console: `performance.memory.usedJSHeapSize` **In Node.js:** - `--inspect`, `heapdump`, `clinic.js`, `process.memoryUsage()` --- ## 10. Short summary | What | Description | |---|---| | **GC (Garbage Collector)** | Mechanism for automatically freeing memory | | **Principle** | Removes objects that can no longer be "reached" | | **Main algorithm** | Mark-and-sweep | | **Leak problem** | When an object is still reachable but not needed | | **Solution** | Break references, clean up timers and listeners | | **Pros** | Simplicity, safety | | **Cons** | Potential pauses and hidden leaks |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.