Explain Closures and this
Interview Question: "Explain closures in JavaScript. How does this work?"
The Closure Answer
Don't say "a function that remembers its scope." Say:
"A closure is formed when a function retains access to its lexical environment after the enclosing function has returned. The inner function holds a reference to the outer function's variable environment â those variables stay alive as long as the closure exists."
The Demonstration
function createCounter() {
let count = 0;
return {
increment: () => ++count,
getCount: () => count,
};
}
const counter = createCounter();
counter.increment();
counter.increment();
counter.getCount(); // 2
// `count` is not accessible from outside but survives because the closures reference it"This is encapsulation without classes.
countis truly private â no way to access it except through the returned methods."
Real-World Impact
"Closures power React hooks â every render creates a new closure, which is why hooks 'see' the state from their render. The stale closure bug happens when an effect captures a value from an old render and never updates."
The this Answer
"
thisin JavaScript is the only dynamically-scoped construct. It's determined by how a function is called, not where it's defined. There are four rules in order of precedence:
newbinding âthisis the new instance- Explicit binding (
call/apply/bind) âthisis the specified object- Implicit binding â
thisis the object before the dot- Default â
undefinedin strict mode,windowin sloppy modeArrow functions are the exception â they have no own
thisand capture it lexically from the enclosing scope."
The Trap Question
const obj = {
name: 'Alice',
greet: () => `Hello, ${this.name}`,
};
obj.greet(); // "Hello, undefined""Arrow function captures
thisfrom the enclosing scope â which is module/global scope, notobj. This is a common mistake: arrow functions should not be used as object methods when you needthisto refer to the object."
Why It Matters
"Understanding
thisexplains why React class components needed.bind(this)in constructors, why arrow functions in class fields work without binding, and why passingobj.methodas a callback loses context."
Red Flags
- Defining closures as "a function inside a function" (too shallow)
- Saying "
thisrefers to the object" without specifying which binding rule - Not knowing arrow functions have no own
this - Not connecting closures to React hooks / stale closure bugs