Memory leaks
- Node.js course
- Expert
- Lesson 22/47
- 5 min
Learn memory leak detection and prevention.
Memory leak
A memory leak is when objects no longer in use are kept in memory. A common cause is a cache that keeps growing. Objects are added but never removed; the cache grows forever.
A detectLeak(cache, limit) function checks this: it returns true if cache.size > limit. Example: with new Set(['x', 'y', 'z']), detectLeak(cache, 2) returns true (3 > 2). detectLeak(cache, 10) returns false (3 < 10). This model checks whether a cache has crossed a limit. In a real application watching cache growth is how you catch a leak early. Set.size gives the number of elements in a set.
Leak detection
In this lesson we write the detectLeak function. The function takes a cache and a limit; it returns true if the cache has crossed the limit. This is a simple way to catch a memory leak with a size check.
Example: const cache = new Set(['x', 'y', 'z']). detectLeak(cache, 2) returns true (3 > 2). detectLeak(cache, 10) returns false. cache.size gives the element count of the set; it is compared with > limit. This pattern is used in real applications to watch cache growth: a limit is set, an alert fires when crossed. The output is true and false; deterministic.
Practice Write the leak detector
Write function detectLeak(cache, limit). Return cache.size > limit. Define const cache = new Set(['x', 'y', 'z']). Print console.log(detectLeak(cache, 2)) and console.log(detectLeak(cache, 10)).
Starter code
// Write a detectLeak function
// Return true if the cache size exceeds the limit
// Call with new Set(['x','y','z']), try two limits
// write hereSample solution
function detectLeak(cache, limit) {
return cache.size > limit;
}
const cache = new Set(['x', 'y', 'z']);
console.log(detectLeak(cache, 2));
console.log(detectLeak(cache, 10));Expected output
true false
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does new Set(['x','y','z']).size return?
new Set(['x','y','z']).size- 2
- 3 Correct answer
- 1
- 0
Explanation: The set has three elements: x, y, z.
2 Match each concept to its description
| Term | Meaning |
|---|---|
Memory leak |
Unused objects remain |
Set.size |
Element count |
limit |
Boundary |
cache |
Cache |
3 Complete the size comparison
return cache.____ > limit;
return cache.size > limit;
Explanation: cache.size gives the element count.