Interview Questions 2
Scope, this, and closures.
The next kind of question checks that you understand how JavaScript works underneath. What will this code print, and why? Let's look at three classics, about var, closures, and this.

- How JavaScript works
- What will it print?
- var, closures, this
var versus let in loops
With var, there's only one i, shared by the whole loop. By the time the timers run, the loop has finished, so they all print three. With let, each loop round gets its own i, so the timers print zero, one, two. Run it.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log("var:", i), 0);
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log("let:", j), 10);
}var: 3 var: 3 var: 3 let: 0 let: 1 let: 2
Closures and this
Make counter returns two functions that share a private count, through a closure. Nothing outside can touch count directly. Then this. A regular method's this is the object it's called on. But when we pull the method out and call it on its own, this is lost, so we get undefined. Run it.
function makeCounter() {
let count = 0;
return { up: () => ++count, get: () => count };
}
const c = makeCounter();
c.up(); c.up();
console.log("count:", c.get(), c.count);
const user = {
name: "Ana",
hello() { return `Hi, ${this?.name}`; },
};
const hello = user.hello;
console.log(user.hello(), "|", hello());count: 2 undefined Hi, Ana | Hi, undefined
Summary
Var shares one variable across a loop, let gives a new one each time. Closures keep private data, and this depends on how a function is called. Next, two practical coding questions.
Key takeaways- var vs let
- Closures hide data
- this = the caller