-1

I am relearning javaScript and ran across this example on mdn about const behaviour:

const MY_FAV = 7;
// it's important to note the nature of block scoping
if (MY_FAV === 7) {
  // this is fine and creates a block scoped MY_FAV variable 
  // (works equally well with let to declare a block scoped non const variable)
  let MY_FAV = 20;

  // MY_FAV is now 20
  console.log('my favorite number is ' + MY_FAV);

  // this gets hoisted into the global context and throws an error
  var MY_FAV = 20;
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

I understand that you cannot redeclare a variable with var after let and const. But the comment says it is hoisted. why does the var MY_FAV = 20; gets hoisted? What actually happens?

Thank you

Edit: this is not a duplicate as there is no discussion about var behaviour in blocks and the differences between let and const inside blocks.

3
  • 2
    var always hoists. This is the (arguably) design flaw that let was designed to fix. var does not use block scoping. Aug 21, 2019 at 11:04
  • Possible duplicate of Variable hoisting Aug 21, 2019 at 11:07
  • @John Coleman thank you for your answer, it pretty much sums it up, but it is not a duplicate as it is specific about scoping.
    – dor
    Aug 21, 2019 at 11:35

1 Answer 1

0

Variables and constants declared with let or const are not hoisted, but the ones declared with var are.

What is happening is var MY_FAV = 20; is getting hoisted and then it tries to be redeclared.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.