-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.

dor
  • 148
  • 1
  • 11
  • 2
    `var` always hoists. This is the (arguably) design flaw that `let` was designed to fix. `var` does not use block scoping. – John Coleman Aug 21 '19 at 11:04
  • Possible duplicate of [Variable hoisting](https://stackoverflow.com/questions/3725546/variable-hoisting) – John Coleman Aug 21 '19 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 '19 at 11:35

1 Answers1

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.

  • `let` and `const` are also hoisted to the top of their scope, `var` is hoisted to the top of the global scope, see https://stackoverflow.com/questions/33198849/what-is-the-temporal-dead-zone – Teemu Aug 21 '19 at 11:34