Question 16
Back to Exercise
What does the following JavaScript code print (console output, as in Node.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!