javascriptfunctionhoistingexecutioncontext

what is the logic behind returning output from second function?


I am new to javascript and understanding hoisting and the functionig of Execution Context in javascript. This code is giving output 8 but why not 3 why it returing 8 from the second function not from the first function?

function a(){
    function b() {
        return 3;
    }

    return b();

    function b() {
        return 8;
   }
} 

console.log(a());

I was expecting 3 from the first function because the function returning 3 is written before the function returning 8.


Solution

  • This is due to hoisting. it happens due to overwriting of second function b(). same function is defined multiple times then javascript takes the last one for execution(remaining all gets overwritten). and the real exection starts only after hoisting. thats why it returned 8

    Thanks,