3
if (true) {
  function foo(){ return 1; }
}
else {
  function foo(){ return 2; }
}
foo();

The above code is an example of function expression and returns 1 in Firefox 28 whereas 2 in Chrome ( expected result). Why is firefox giving wrong result ?

Vivek Chandra
  • 4,240
  • 9
  • 33
  • 38
  • could be `chrome` loads the functional expressions before executing any line of code, whereas `firefox` does when its interpreter reaches the line of declaration of the functions? – BatScream Jan 03 '15 at 08:19
  • If chrome loads these expressions before hand, the second `foo()` declaration would replace its first declaration? – BatScream Jan 03 '15 at 08:21
  • 1
    [Conditionally declared functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function#Conditionally_created_functions) in FF. Notice, that what you have, is a function declaration, not an expression. – Teemu Jan 03 '15 at 08:25

1 Answers1

0

It is a case of function hoisting. Any function declared with an identical function name, the last function of that name will gain precedence and be used even if it is null. In most cases function declaration is processed before the script executes, however, with Firefox this isn't the case, it takes it as it comes within an if block.

  • 1
    "[FF] takes it as it comes", yes, but only in a case the function declaration is within an `if` block. FF hoists declared functions as well as other browsers when declared outside of an `if` block. – Teemu Jan 03 '15 at 08:29