Description
The solution for the task "Function in if" under "closures" chapter is incorrect. It does not give error and alerts "Hello, John".
The explanation with correct solution should explain "hoisting" of function declarations. In the example we are using function declaration for the function "sayHi", which roughly translates to
`let phrase = "Hello";
if (true) {
let user = "John";
var sayHi = function () {
alert(${phrase}, ${user}
);
}
}
sayHi();`
(This translation is just to explain the code here, I am aware function declaration and expression are different things)
Now since "var" is not bound with block scope of "if", it will be accessible outside and so we get the alert.
You can add this to explain it more clearly
`let phrase = "Hello";
if (true) {
let user = "John";
let sayHi = function () {
alert(${phrase}, ${user}
);
}
}
sayHi();`
Here we are using "let" and that is bound in the block scope of "if", so it is not accessible outside and will throw a referenceError.
P.S. - I am a fan of content and flow of javascript.info since a long time and you are doing a terrific job. Kudos.