0
0
Node.jsframework~10 mins

Common memory leak patterns in Node.js - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a timer that repeats every second.

Node.js
setInterval(() => { console.log('Tick'); }, [1]);
Drag options to blanks, or click blank then click option'
A10
B100
C1000
D5000
Attempts:
3 left
💡 Hint
Common Mistakes
Using 100 instead of 1000 causes the timer to tick too fast.
Using 5000 makes the timer tick every 5 seconds, not 1.
2fill in blank
medium

Complete the code to remove the event listener properly.

Node.js
emitter.on('data', handler);
// Later remove listener
emitter.[1]('data', handler);
Drag options to blanks, or click blank then click option'
AremoveListener
BaddListener
Cemit
Donce
Attempts:
3 left
💡 Hint
Common Mistakes
Using addListener again adds more listeners, causing leaks.
Using emit triggers events but does not remove listeners.
3fill in blank
hard

Fix the error in the code to avoid a memory leak caused by global variables.

Node.js
global.cache = {};
function addToCache(key, value) {
  [1].cache[key] = value;
}
Drag options to blanks, or click blank then click option'
Awindow
Bcache
Cthis
Dglobal
Attempts:
3 left
💡 Hint
Common Mistakes
Using window causes errors because it is a browser object.
Using this may not refer to the global object here.
4fill in blank
hard

Fill both blanks to create a WeakMap and store an object without preventing garbage collection.

Node.js
const cache = new [1]();
const obj = {};
cache.[2](obj, 'data');
Drag options to blanks, or click blank then click option'
AWeakMap
BMap
Cset
Dadd
Attempts:
3 left
💡 Hint
Common Mistakes
Using Map keeps strong references, causing leaks.
Using add is not a method of Map or WeakMap.
5fill in blank
hard

Fill all three blanks to create a closure that does not cause a memory leak by holding unnecessary references.

Node.js
function createCounter() {
  let count = 0;
  return function() {
    count [1] 1;
    return [2];
  };
}
const counter = createCounter();
counter(); // [3]
Drag options to blanks, or click blank then click option'
A+=
Bcount
C1
D++
Attempts:
3 left
💡 Hint
Common Mistakes
Using ++ alone without return causes confusion.
Returning 1 always does not reflect the count.