LearnFrenzy
Sign in Take a free test

Scope and Hoisting · Predict the Output · Question 2

Which x is incremented? Answer, explanation & discussion

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

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

main.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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links