LearnFrenzy
Sign in Take a free test

Scope and Hoisting · Predict the Output · Question 18

Assigning before a var declared in a block Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 18 Back to Exercise

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

main.js
function f() {
  x = 5;
  {
    var x;
  }
  return x;
}
console.log(f(), typeof x);
  • A 5 number
  • B undefined undefined
  • C ReferenceError
  • D 5 undefined Correct
Correct Answer: Option D

var x is hoisted to the top of f (blocks do not limit var), so x = 5 assigns the local variable. No global x is created.

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