2

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?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Nattttt
  • 23
  • 4
  • 6
    `const` (and `let`) are hoisted, but they're affected by the temporal dead-zone where they can't be accessed before they're initialized: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz – Nick Parsons Aug 08 '21 at 10:45

1 Answers1

4

Variables declared with let and const are also hoisted, but unlike for var the variables are not initialized with a default value of undefined. Until the line in which they are initialized is executed, any code that accesses these variables will throw an exception.

MDN DOCS

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64