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 ?

3
  • 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? Commented Jan 3, 2015 at 8:19
  • If chrome loads these expressions before hand, the second foo() declaration would replace its first declaration? Commented Jan 3, 2015 at 8:21
  • 1
    Conditionally declared functions in FF. Notice, that what you have, is a function declaration, not an expression. Commented Jan 3, 2015 at 8:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

"[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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.