Tell us what’s happening:
I was trying to test some other cases out and got stuck.
Scenario:
1) if I comment out var outerWear = "sweater"; this line, then both console outputs “T-Shirt” – > make sense
2) if I uncomment that line, the the first console output says “undefined” and the second says “sweater” --> doesn’t make sense to me
QUESTION: (in Scenario 2) Why isn’t the first line of console output “T-Shirt” since it’s referring to the global scope variable?
Thanks for taking your time.
-Adina
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/86.0.4240.75 Safari/537.36.
Thanks for pointing me to the exact information I’m looking for!
Quick summary of the concept of hoisting:
Hoisting, in the context of JS, is the idea that variable and function declarations are physically moved to the top of the code to be executed first.
However, in reality, hoisting is done by putting the variable and function declarations into memory during the compile phase. And the declarations stay exactly where you typed them in your code.
Hoisting only works for declaration in JavaScript.
Declarations using let and const are also not hoisted.
So in my original situation:
// 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();
The first console output would print out “undefined” since the local variable outwear is already declared during compiling (and due to hoisting), but hasn’t been given a value yet.