I have some code below. I hope it can log a
and b
correctly, but as the result, it logs a
as 1, b
is not defined with error:
Uncaught ReferenceError: b is not defined
function foo(){
var a = 1
let b = 2
(function bar() {
console.log(a)
console.log(b)
}())
}
console.log(foo());
If I change the code to make the bar
as a function declaration, every thing is fine
function foo(){
var a = 1
let b = 2
function bar() {
console.log(a)
console.log(b)
}
bar()
}
console.log(foo());
I know some thing about function scope, block scope, hoisting. But I really don't understand what happens make the b
to be 'not defined'
All the code above was run in the Chrome 66's devTools