Loading content…
Loading content…
Master closures, prototypical inheritance chains, modern ES6-ES15 APIs, and memory leak prevention techniques
function createCounter() {
let count = 0; // Private state variable
return {
increment: () => {
count++;
return count;
},
decrement: () => {
count--;
return count;
}
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
// The variable "count" cannot be accessed directly from the outside!
class keyword is syntactic sugar over prototype chains.[[Prototype]] or accessed via Object.getPrototypeOf).const animal = {
eats: true,
walk() {
console.log("Animal walking...");
}
};
const dog = Object.create(animal); // Links dog's prototype to animal
dog.barks = true;
dog.walk(); // "Animal walking..." (Found by traveling up the prototype chain!)
console.log(dog.eats); // true
object.__proto__) until it either finds the property or reaches the end (null).?.) & Nullish Coalescing (??):
// Prevents crash if user or profile is missing. Nullish coalescing checks for null/undefined only.
const theme = user?.profile?.settings?.theme ?? "light";
structuredClone):
Historically, deep-copying objects required importing loadash or running JSON.parse(JSON.stringify(obj)), which crashes on dates or regex. Use native structuredClone:
const deepCopy = structuredClone(originalObject);
WeakMap keys must be objects, and they hold weak references, allowing the garbage collector to clean them up if there are no other references to them.
const metadata = new WeakMap();
let element = document.getElementById("main-card");
metadata.set(element, { clicked: false });
// If element is removed from DOM and dereferenced:
element = null; // The WeakMap automatically releases memory for both key and metadata!
window or global execution context).// ❌ BAD: React hook without clean-up
useEffect(() => {
window.addEventListener("resize", handleResize);
}, []);
// ✅ GOOD: Always remove listeners on unmount
useEffect(() => {
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
setInterval callback continues executing even if the page that spawned it is closed:// ❌ BAD: Timer runs forever
setInterval(() => {
fetchData();
}, 1000);
// ✅ GOOD: Clear interval
const timerId = setInterval(fetchData, 1000);
// Clear using clearInterval(timerId) when route changes or component unmounts.
const elements = {
button: document.getElementById("action-btn")
};
document.body.removeChild(elements.button);
// elements.button still references the node! Fix: elements.button = null;
Senior Developer Wisdom
Common Pitfall
JavaScript Memory & Core Checklist
structuredClone) and dynamic properties checking (?.).Marking it complete updates your roadmap progress percentage.