Here's another way to verify that let
and const
variables do get hoisted.
If we run the below code in Chrome console, we can see that under the scripts
tab, only y will be present:
debugger;
console.log(x)
console.log(y)
let y = 10;
Script
y: undefined
If there were no hoisting happening with let
, it should have "seen" y
also.
If we run the same code in FireFox console, the message is even clearer—it says y is uninitialized (as opposed to y is undefined if we had used var
instead of let
. Also note that it shows under the Block
tab, as opposed to Scripts
tab in Chrome, making it clear that it's a block-scoped variable.
Block
y: (uninitialized)
The above makes it clear that both var
and let/const
variables are hoisted but var
variables are initilaized with undefined
whereas let/const
variables are uninitialized (not given any value at all—even undefined
—until execution reaches the "declaration*" line.