en.javascript.info icon indicating copy to clipboard operation
en.javascript.info copied to clipboard

Advanced working with function: Function in if

Open aman20212 opened this issue 11 months ago • 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 avatar Feb 08 '25 10:02 aman20212

@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 avatar Feb 09 '25 13:02 abhishekabhiRaj

@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.

aman20212 avatar Feb 09 '25 17:02 aman20212

https://javascript.info/strict-mode#should-we-use-strict

" All examples in this tutorial assume strict mode unless (very rarely) specified otherwise. "

joaquinelio avatar Feb 15 '25 16:02 joaquinelio