Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Advanced working with function: Function in if #3812

Open
aman20212 opened this issue Feb 8, 2025 · 3 comments
Open

Advanced working with function: Function in if #3812

aman20212 opened this issue Feb 8, 2025 · 3 comments

Comments

@aman20212
Copy link

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.

@abhishekabhiRaj
Copy link

@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" ?

@aman20212
Copy link
Author

aman20212 commented Feb 9, 2025

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

@joaquinelio
Copy link
Member

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants