Tell us what’s happening:
Describe your issue in detail here.
Can anyone explain to me what the global “outerWear” becomes undefined if a new local variable with the same name is declared after it?
**Your code so far**
var outerWear = "T-Shirt";
function myOutfit() {
console.log(outerWear); //print undefined
var outerWear="sweater";
console.log(outerWear); //prints sweater
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/90.0.4430.212 Safari/537.36.
Sure. But it is not you think. This isn’t a scope issue, it’s a hoisting issue.
Because you used a var to define that local variable, as opposed to a let or const, the way the variable is created changes. Had you used let inside the function, it would have done what you expect, but a var allocates the memory for a variable before the function body is run. So at that point, you are referencing the local variable, even though you haven’t assigned a value to it yet.
Google " javascript var hoisting" to read more about it.