Bird
0
0

Consider this code snippet:

medium📝 component behavior Q13 of 15
Node.js - Debugging and Profiling
Consider this code snippet:
const cache = {};
function addToCache(key, value) {
  cache[key] = value;
}
addToCache('user1', {name: 'Alice'});
addToCache('user2', {name: 'Bob'});
console.log(Object.keys(cache).length);

What will be the output and what memory issue might this cause if keys are never removed?
A0; No memory leak because cache is empty
B2; Memory leak due to unbounded cache growth
CError; Syntax error in code
DUndefined; cache is not defined
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the code output

    The cache object stores two keys: 'user1' and 'user2'. Object.keys(cache).length returns 2.
  2. Step 2: Identify memory issue

    Since keys are never removed, cache grows indefinitely, causing a memory leak.
  3. Final Answer:

    2; Memory leak due to unbounded cache growth -> Option B
  4. Quick Check:

    Cache size = 2, leak if keys never removed [OK]
Quick Trick: Uncleared caches cause leaks; count keys to check size [OK]
Common Mistakes:
  • Thinking cache is empty initially
  • Assuming syntax error without checking code
  • Confusing undefined with empty object

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes