LearnFrenzy
Sign in Take a free test

Scope and Hoisting · Predict the Output · Question 16

A let copy inside a var loop Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 16 Back to Exercise

What does the following JavaScript code print (console output, as in Node.js)?

main.js
var fns = [];
for (var i = 0; i < 3; i++) {
  let j = i;
  fns.push(() => j);
}
console.log(fns.map((f) => f()), i);
  • A [ 3, 3, 3 ] 3
  • B [ 0, 1, 2 ] 2
  • C [ 2, 2, 2 ] 3
  • D [ 0, 1, 2 ] 3 Correct
Correct Answer: Option D

The loop body is a block, so each pass creates a new let j holding that pass's value. i itself is a single function-scoped var that ends at 3.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links