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.
var
always hoists. This is the (arguably) design flaw thatlet
was designed to fix.var
does not use block scoping.