1
var x = 5;
function y(){
  x=10;
  return
  function x(){}

}


console.log(x);   //5
console.log(y());   //undefined
console.log(x);   //5

if i remove the line function x(){} then expected output will be logged.

  • 4
    `function x(){}` is hoisted which means there are 2 `x` variables in your code: one in the global scope and the other is local to the `y` function scope. Assigning `10` to `x` actually assigns to the local `x`, not the global one. That is why, even after the `y` function call, global `x` is still `5`. – Yousaf Aug 18 '21 at 15:14
  • What do you expect `y()` to return other than `undefined`? – Adil Bimzagh Aug 18 '21 at 15:15
  • 3
    @AdilBimzagh clearly OP expects it to return `undefined`. – VLAZ Aug 18 '21 at 15:16
  • see https://stackoverflow.com/questions/63412650/why-is-this-javascript-snippet-logging-1 – Ramesh Reddy Aug 18 '21 at 15:16
  • @VLAZ Oops my bad! – Adil Bimzagh Aug 18 '21 at 15:18
  • @Yousaf your comment is explanatory. But anything written after return statement shouldn't be executed right? so function x(){} shouldn't be an issue? –  Aug 18 '21 at 15:28
  • 3
    Hoisting happens _before_ the step-by-step execution of the code. You are right, anything after `return` isn't executed BUT the variable/function declarations are processed _before_ any code is executed; variable `x` is defined is the local scope of function `y` _before_ you assign value `10` to `x` which overwrites its initial value, i.e. a function. – Yousaf Aug 18 '21 at 15:33
  • @MonsJoseph "*anything written after return statement shouldn't be executed right? so function x(){} shouldn't be an issue?*" if that were the case, then hoisting wouldn't actually work because you would need to reach a function declaration in order to be "executed" and thus you'd be able to call it. So code like `fn(); function fn() {}` wouldn't work. That's not the case, since hoisting happens *before* code is executed. – VLAZ Aug 18 '21 at 16:11

0 Answers0