Complete the code to create a new buffer of 10 bytes in Node.js.
const buffer = Buffer.[1](10);
The Buffer.alloc(size) method creates a new buffer of the specified size filled with zeros. This is the safe way to allocate memory in Node.js.
Complete the code to free up memory by clearing a large object reference.
let largeObject = { data: 'some large data' };
// When done, set to [1] to help garbage collectionnull is clearer for intent.Setting a variable to null removes the reference to the object, allowing Node.js garbage collector to reclaim memory.
Fix the error in the code to avoid memory leaks by removing event listeners properly.
const EventEmitter = require('events'); const emitter = new EventEmitter(); function onData() { console.log('Data received'); } emitter.on('data', onData); // To prevent leaks, remove listener with emitter.[1]('data', onData);
removeEvent which does not exist.deleteListener which is not a method.The off method is the modern way to remove event listeners in Node.js, preventing memory leaks.
Fill both blanks to create a WeakMap and add an object key with a value.
const [1] = new [2](); const objKey = {}; weakMap.set(objKey, 'value');
Map instead of WeakMap which does not allow garbage collection of keys.weakmap which is not a valid constructor.A WeakMap allows keys to be garbage collected if there are no other references. Naming the variable weakMap is a common convention.
Fill all three blanks to create a memory-efficient cache using a WeakMap and add an entry.
const [1] = new [2](); const user = { id: 1 }; [3].set(user, { name: 'Alice' });
Map instead of WeakMap which keeps strong references.Using a WeakMap named cache helps store data linked to objects without preventing garbage collection.