Bird
Raised Fist0
Node.jsframework~20 mins

Memory management best practices in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Memory Mastery in Node.js
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Understanding Garbage Collection in Node.js
What happens when an object in Node.js is no longer referenced by any part of the program?
AThe object is immediately deleted from memory by the programmer.
BThe object remains in memory until the program ends.
CThe object is moved to a special memory area for later use.
DThe garbage collector automatically frees the memory used by the object.
Attempts:
2 left
💡 Hint
Think about how automatic memory cleanup works in modern programming environments.
❓ component_behavior
intermediate
2:00remaining
Effect of Large Buffers on Memory
Consider this Node.js code snippet that creates a large buffer inside a function. What is the likely effect on memory after the function finishes if the buffer is not returned or stored elsewhere?
Node.js
function createBuffer() {
  const buf = Buffer.alloc(10 * 1024 * 1024); // 10MB buffer
  // do something with buf
}
createBuffer();
AThe buffer is eligible for garbage collection after the function ends because it is not referenced.
BThe buffer is freed only when the program exits.
CThe 10MB buffer remains in memory indefinitely, causing a memory leak.
DThe buffer is copied to a global variable automatically.
Attempts:
2 left
💡 Hint
Think about what happens to local variables after a function finishes if they are not saved.
🔧 Debug
advanced
2:00remaining
Identifying Memory Leak Cause
Which option best explains why this Node.js code causes a memory leak?
Node.js
const cache = {};
function addToCache(key, value) {
  cache[key] = value;
}

setInterval(() => {
  addToCache(Date.now(), new Array(1000000).fill('*'));
}, 1000);
AThe setInterval function is not cleared, causing multiple timers to run.
BThe cache object keeps growing without removing old entries, preventing garbage collection.
CThe array is too large to be stored in memory, causing immediate crash.
DThe Date.now() function returns the same value every second, overwriting cache keys.
Attempts:
2 left
💡 Hint
Think about what happens when you keep adding data to an object without removing anything.
📝 Syntax
advanced
2:00remaining
Correct Use of Weak References to Avoid Memory Leaks
Which code snippet correctly uses a WeakMap to store objects without preventing their garbage collection?
A
const wm = new WeakMap();
const obj = {};
wm.set(obj, 'value');
B
const wm = new WeakMap();
const obj = {};
wm.set('key', obj);
C
const wm = new WeakMap();
const obj = {};
wm.set({}, 'value');
D
const wm = new WeakMap();
wm.set('key', 'value');
Attempts:
2 left
💡 Hint
Remember that WeakMap keys must be objects, not strings or primitives.
❓ state_output
expert
2:00remaining
Memory Usage After Manual Buffer Nullification
What is the expected behavior of the memory usage after running this Node.js code?
Node.js
let bigBuffer = Buffer.alloc(50 * 1024 * 1024); // 50MB buffer
console.log(process.memoryUsage().heapUsed);
bigBuffer = null;
setTimeout(() => {
  console.log(process.memoryUsage().heapUsed);
}, 1000);
AThe program will crash due to freeing memory manually.
BThe second memory usage log will show a significantly lower heapUsed value because the buffer is freed.
CThe second memory usage log will be the same or slightly higher because garbage collection may not have run yet.
DThe buffer remains in memory because setting to null does not affect references.
Attempts:
2 left
💡 Hint
Think about when garbage collection runs and how memory usage is reported.

Practice

(1/5)
1. Which of the following is a good practice to help Node.js manage memory efficiently?
easy
A. Use streams to process large data instead of loading it all at once
B. Keep all data in global variables for easy access
C. Avoid using asynchronous functions to reduce complexity
D. Never clear timers or intervals once set

Solution

  1. Step 1: Understand memory usage with large data

    Loading large data all at once uses a lot of memory. Streams process data in small chunks, saving memory.
  2. Step 2: Evaluate options for memory efficiency

    Using global variables or never clearing timers can cause memory leaks. Avoiding async functions doesn't help memory.
  3. Final Answer:

    Use streams to process large data instead of loading it all at once -> Option A
  4. Quick Check:

    Streams save memory by chunking data [OK]
Hint: Streams handle big data efficiently, avoid globals [OK]
Common Mistakes:
  • Thinking global variables are memory efficient
  • Ignoring the need to clear timers
  • Believing async functions cause memory leaks
2. Which syntax correctly clears a timeout timer in Node.js to prevent memory leaks?
easy
A. clearTimeout(timerId);
B. clearInterval(timerId);
C. stopTimer(timerId);
D. removeTimer(timerId);

Solution

  1. Step 1: Identify the correct function to clear a timeout

    Node.js uses clearTimeout() to stop timers set by setTimeout().
  2. Step 2: Match function to timer type

    clearInterval() clears intervals, not timeouts. stopTimer() and removeTimer() are invalid.
  3. Final Answer:

    clearTimeout(timerId); -> Option A
  4. Quick Check:

    clearTimeout() stops setTimeout timers [OK]
Hint: Use clearTimeout for setTimeout timers [OK]
Common Mistakes:
  • Confusing clearTimeout with clearInterval
  • Using non-existent functions like stopTimer
  • Not clearing timers at all
3. What will be the output of the following code snippet regarding memory usage?
const data = [];
setInterval(() => {
  data.push(new Array(1000000).fill('x'));
  console.log('Data length:', data.length);
}, 1000);
medium
A. Data length stays at 1, memory usage is stable
B. Data length increases indefinitely, causing memory to grow
C. Throws an error after first interval
D. Data length resets to zero every second

Solution

  1. Step 1: Analyze the setInterval behavior

    Every second, a large array is added to the data array, increasing its size.
  2. Step 2: Understand memory impact

    Since data keeps growing without clearing, memory usage grows indefinitely, risking leaks.
  3. Final Answer:

    Data length increases indefinitely, causing memory to grow -> Option B
  4. Quick Check:

    Growing arrays without cleanup increase memory [OK]
Hint: Adding large arrays repeatedly grows memory [OK]
Common Mistakes:
  • Assuming data length resets automatically
  • Expecting an error without memory limits
  • Thinking memory stays stable without cleanup
4. Identify the memory leak issue in this Node.js code:
let cache = {};
function addToCache(key, value) {
  cache[key] = value;
}
setInterval(() => {
  addToCache(Date.now(), new Array(1000000).fill('leak'));
}, 1000);
medium
A. Arrays are too small to cause memory issues
B. Using Date.now() as key causes syntax error
C. The cache object grows indefinitely without cleanup
D. setInterval is cleared automatically, no leak

Solution

  1. Step 1: Examine cache growth

    Each second, a new large array is added with a unique key, so cache size grows endlessly.
  2. Step 2: Understand memory leak cause

    Without removing old entries, memory usage increases causing a leak.
  3. Final Answer:

    The cache object grows indefinitely without cleanup -> Option C
  4. Quick Check:

    Uncleared caches cause memory leaks [OK]
Hint: Uncleared caches with growing keys leak memory [OK]
Common Mistakes:
  • Thinking Date.now() causes syntax errors
  • Assuming setInterval clears itself
  • Underestimating array size impact
5. You have a Node.js app that processes large files. Which combined approach best prevents memory leaks and high memory use?
hard
A. Process files in memory, use setInterval without clearing, and avoid streams
B. Load entire files into memory, keep global caches, and never clear timers
C. Use synchronous file reads, keep data in global variables, and clear timers
D. Use streams to process files, clear timers after use, and avoid global caches

Solution

  1. Step 1: Choose memory-efficient file processing

    Streams process large files in chunks, reducing memory use compared to loading whole files.
  2. Step 2: Manage timers and caches properly

    Clearing timers prevents leaks. Avoiding global caches stops memory from growing endlessly.
  3. Final Answer:

    Use streams to process files, clear timers after use, and avoid global caches -> Option D
  4. Quick Check:

    Streams + clear timers + no globals = best memory practice [OK]
Hint: Combine streams, clear timers, avoid globals for best memory [OK]
Common Mistakes:
  • Loading full files into memory
  • Not clearing timers causing leaks
  • Using global caches without cleanup
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard