Search code examples
javascripthoisting

When declaring two functions with the same name in a global scope, the second one gets executed


function getResult(){
return 1;
}

alert(getResult()); //alerts 2

function getResult(){
return 2;
}

could anyone explain, how does this happen?


Solution

  • The function you declare last is seen as the newest one. The newest one always gets executed first. The reason you can call before its declared is because of hoisting.

    Hoisting in a nutshell :

    Before your function is executed all variables and functions are registered and made available, so you can call them from before their declaration.

    during the phase when all variables are being made available the latest will override the oldest. Which is why your second function is called. The first one was simply overwritten.

    Notice that this doesn't apply to const and let. Only functions and variables declared with function and var