Question 2
Back to Exercise
What does the following JavaScript code print (console output, as in Node.js)?
let x = 1;
function a() {
let x = 2;
return function b() {
x++;
return x;
};
}
const f = a();
console.log(f(), f(), x);
- A 3 4 1 Correct
- B 2 3 1
- C 3 4 3
- D 2 2 1
Correct Answer: Option A
b updates the nearest x – the one in a(), which survives in the closure – so it goes 3, 4. The global x is untouched.
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!