Search code examples
javascriptfunction-pointersexecution

Order of javascript execution


I read that

JavaScript caches declared functions before any other variables, after this, it goes back to the top of the scope and runs variable definitions and functions calls in the order that they appear

And I don't understand this example

//bob first initialization
function bob()
{
    alert('bob');
}
 
//set jan to bob via reference
var jan = bob;

//set bob to another function
function bob()
{
    alert('newbob');
}
 
jan(); //alerts 'bob'
bob(); //alerts 'newbob'

both bob() function are declared and cached before execution. Why is it then that jan() alerts 'bob' and not 'newbob'? When jan was initialized bob() had already been re-declared.

Any ideas? THanks


Solution

  • because jan points to the first declaration of bob (as a pointer) and not the new declared bob you need to set jan = bob; after the second declaration

    not so sure though.