Programs & Examples
Scope and Hoisting · Study material
Independent ID generators
Each call to createIdGenerator creates a new scope with its own next counter, so the order and ticket sequences never interfere.
// Independent ID generators: each call creates a new private counter
function createIdGenerator(prefix, start = 1) {
let next = start;
return () => `${prefix}-${String(next++).padStart(4, "0")}`;
}
const orderId = createIdGenerator("ORD");
const ticketId = createIdGenerator("TKT", 500);
console.log(orderId(), orderId(), ticketId(), orderId(), ticketId());
ORD-0001 ORD-0002 TKT-0500 ORD-0003 TKT-0501
Lexical scope in action
The lexical-scope example on the Introduction tab shows the interview classic: show() reads the global level, not run()'s local one.