Closures, Stack vs. Heap & Big O Notation in JavaScript and TypeScript
A practical walkthrough of my JS/TS study notes on lexical closures, Stack vs. Heap memory allocation, and Big O complexity with TypeScript examples.
I brought together three JavaScript and TypeScript fundamentals from my LinkedIn study series because they show up constantly in both technical interviews and real-world React debugging.
1. Lexical Closures
A Closure happens when an inner function remembers variables from its outer lexical scope even after the outer function has finished running—the exact mechanism behind private factories and React hook stale-closure bugs.
function createCounter(initial = 0) {
let value = initial;
return function increment(): number {
value += 1;
return value;
};
}
const next = createCounter(10);
next(); // 11
next(); // 122. Stack vs. Heap (Primitives vs. References)
Primitives (string, number, boolean) copy by value on the Stack, whereas objects and arrays live on the Heap and variables hold a pointer reference.
let a = 10;
let b = a;
b = 20; // `a` stays 10
const user = { name: "Miguel" };
const alias = user;
alias.name = "Riquelme"; // mutates `user.name` tooThat is why React state updates require new object/array references or ES2023 immutable helpers such as toSorted() and toReversed().
3. Practical Big O Notation
Switching an Array.includes() lookup inside a loop (O(n²)) to a Set.has() lookup (O(n)) is one of the simplest everyday performance wins in front-end code:
// O(n²)
const slow = ids.filter((id) => blockedList.includes(id));
// O(n)
const blockedSet = new Set(blockedList);
const fast = ids.filter((id) => blockedSet.has(id));Final Thoughts
Knowing how closures, memory references, and lookup complexity behave prevents subtle bugs and sluggish UI renders long before reaching for heavy optimizations.
Miguel Riquelme
Front-end Engineer. Software Engineering MBA student at USP/Esalq.