I am learning Javascript and I got into the hoisting/scoping part. I got some questions that I really hope somebody can help me to clarify and here is my example:
So these works normally due to hoisting - the firstName variable is in Global Scope or function can be called before we declare the function:
function test() {
console.log(firstName);
}
const firstName = 'a';
test();
OR
const firstName ='a';
test();
function test (){
console.log(firstName)
}
However, if I swap the order of firstName and test(), the code does not work anymore:
function test() {
console.log(`${firstName}`)
};
test();
const firstName = 'a';
According to the hoisting, I thought the firstName variable is in the Global Scope. Thereby, the test function should have been able to look up at the variable firstName when it is executed.
But why in the case above, it does not work?
Is there anything wrong with my understanding of hoisting/scoping?