Var declaration return undefined in function scope

In the code below the first log statement returns undefined. I thought it should reference the global variable and print it.
It prints T-shirt once the var is removed in the next line (if we are overwriting the global variable)
Why would a variable declaration change the value of the variable value before it
Your code so far


// Setup
var outerWear = "T-Shirt";

function myOutfit() {
// Only change code below this line
console.log(outerWear)
var outerWear = "sweater"
console.log(outerWear)

// Only change code above this line
return outerWear;
}

myOutfit();
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36.

Challenge: Global vs. Local Scope in Functions

Link to the challenge:

Behind the scenes this is what is happening. It is called hoisting and var is function scoped.

function myOutfit() {
   var outerWear
   // Only change code below this line
   console.log(outerWear)
   outerWear = "sweater"
   console.log(outerWear)

   // Only change code above this line
   return outerWear;
}

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.