Advanced working with function: Function in if
Opened this issue · 3 comments
Function in if
let phrase = "Hello";
if (true) {
let user = "John";
function sayHi() {
alert(${phrase}, ${user});
}
}
sayHi();
As mentioned, in the solution:
The result is an error.
The function sayHi is declared inside the if, so it only lives inside it. There is no sayHi outside.
But, this is wrong.
once the function is called, it will give us "Hello John" and the explanation is quite simple.
There, won't be any error.
@aman20212 I have executed same code but its giving error in strict mode only , if I am not using strict mode sayHi() is getting executed from outside. In "use strict" sayHi will give ReferenceError, Are you using "use strict" ?
@abhishekabhiRaj Agree with your explanation.
But, it's confusing, for beginners.
The solution mentioned will only work when the code in problem is executed using "use strict" directive.
Else, it will work fine.
javascript.info should update the same.
https://javascript.info/strict-mode#should-we-use-strict
" All examples in this tutorial assume strict mode unless (very rarely) specified otherwise. "