How do global variable work in javascript (callback)?

Your code is being executed from the top of the page as following :
username gets declared and set to = null -> myFunction_1() get’s defined -> myFunction_1() gets called -> username gets set to 'pippo' -> console.logs "1: pippo" -> console.logs "2: pippo" -> myFunction_2() get’s defined -> myFunction_2() gets called -> console.logs "3: pippo" this happens in this sequence assuming that this code runs, which it does not in your case.

Assuming that salvaUsername() looks like function salvaUsername(){ return username; } username is null as it have never reached the point of assignment that happens in myFunction_1(). (It’s actually surprising that output is not undefined but null).

In this case myFunction_1() never runs so username doesn’t get set to 'pippo' hence the outcome.

Leave a Comment