AI Hints
Home›JavaScript Tutorial›Interview Questions
JavaScript · Lesson 131 of 138

Interview Questions 2

Scope, this, and closures.

⏱ 2 min read▶ Video at 2:37:06🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Interview Questions 2
From the video: Interview Questions 2
  • 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.

app.jsjavascript
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);
}
Output
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.

app.jsjavascript
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());
Output
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
Next up: Interview Questions 3 — flatten and memoize