0

I am bit confuse to understand logic of this function

function foo(){
  var bar = function() {
    return 3;
  };
  function bar() {
    return 8;
  };
return bar();
}
alert(foo());

alert(foo()); print 3. But as per my logic

var bar = function() {
    return 3;
  };

is local function because of var keyword and

function bar() {
    return 8;
  };

is global function for function foo(). Also java script execute line by line so the function with same name which call last should print output. So as per my logic this function should print 8. But it is printing 3.

Also the another example

function foo(){
  return bar();
  var bar = function() {
    return 3;
  };
  var bar = function() {
    return 8;
  };
}
alert(foo());

This function throw error Uncaught TypeError: bar is not a function Why it is giving error. Can anyone please solve my confusion with both function? Sorry if my logic goes wrong please correct me. Thanks in advance.

Pooja
  • 105
  • 4
  • 16
  • 1
    Both are local. But `function bar` is being *hoisted* (look it up…). – deceze Apr 06 '17 at 07:28
  • functions are hoisted before declarations happens. – Nina Scholz Apr 06 '17 at 07:30
  • 1
    [var functionName = function() {} vs function functionName() {}](//stackoverflow.com/q/336859) – Tushar Apr 06 '17 at 07:30
  • @deceze: I looked at that one, but the `return` screws it up. But Pooja - [Somewhere in here](/search?q=%5Bjs%5D+function+hoisting) you'll find the answer to the above, which is that the declaration happens *first*, and then you overwrite the function returning `8` with the one returning `3` afterward. – T.J. Crowder Apr 06 '17 at 07:32
  • @T.J.C I think the top answer explains the basic concept pretty well and can easily be applied here. – deceze Apr 06 '17 at 07:34
  • @deceze I understand why first function return 3 but I am still confuse about 2nd function which throw error Uncaught TypeError: bar is not a function – Pooja Apr 06 '17 at 09:50
  • Because no function is assigned to `bar` by the time you're trying to call it, because assignments are *not* hoisted. – deceze Apr 06 '17 at 10:18

0 Answers0