call(back)

Predict the Output: var Hoisting With Shadowing

What does logIt() print? Explain why.

var text = "outside";
function logIt() {
  console.log(text);
  var text = "inside";
}
logIt();

Hints

Hint 1

var declarations are hoisted to the top of the function and initialized to undefined.

Solution

Show the approach

Answer: undefined

The inner var text is hoisted to the top of logIt and initialized to undefined, shadowing the outer variable. With let or const the same code would throw a ReferenceError instead — the temporal dead zone.

Asked at