+ 3

Everyone,need a help! Look at the code below.Can you guys explain that why the function "sayhi" is not defined?thanks

let phrase = "Hello"; if (true) { let user = "John"; function sayHi() { alert(`${phrase}, ${user}`); } } sayHi();

19th Nov 2020, 2:10 AM
Nishino
Nishino - avatar
3 Answers
+ 4
ES5 forbids declaring functions inside blocks, so the code doesn't work in strict mode (see attachment) In nonstrict mode something strange happens - the function is not hoisted to the top like it was pre ES5, so it gets access to the block scope user variable. Also making the if condition false skips definition of the function, resulting in an error. So nonstrict mode (at least on sololearn) neither informs you of an error, nor preserves backwards compatibility https://code.sololearn.com/W3DBKY84Wzl5/?ref=app
19th Nov 2020, 2:31 AM
Volodymyr Chelnokov
Volodymyr Chelnokov - avatar
+ 4
Volodymyr Chelnokov thanks! Now I know this is the problem of strict mode
19th Nov 2020, 2:42 AM
Nishino
Nishino - avatar
0
may can be friends with u?
20th Nov 2020, 9:12 PM
Shabab “Bassam
Shabab “Bassam - avatar