Why welcome() works outside block? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why welcome() works outside block?

JS code: let age = 16; if(age > 18) { function welcome() { console.log("Welcome!"); } welcome(); } else { function welcome() { console.log("Not welcome!"); } welcome(); } welcome(); // “Not welcome!” how? Should I not be able to call welcome() outside the if-else block, why it’s executing with no errors?

21st Sep 2022, 10:05 PM
Patrick Ascanoa
Patrick Ascanoa - avatar
2 Answers
+ 3
And where did you get that there must be an error? Have you defined the function in the "else" block? Yes, determined. Now you can call it anywhere, even in another function.
21st Sep 2022, 10:47 PM
Solo
Solo - avatar
+ 1
<DD> That's right, because you assign a function to a constant variable, and it, like the "let" variable, is local.
22nd Sep 2022, 6:49 AM
Solo
Solo - avatar