5

The code below will get different in Browser and Node.js.

Result of browser is a.

Result of Node.js is b.

if (1) {
    function foo() { return 'a'; }
} else {
    function foo() { return 'b'; }
}

console.log(foo());

Although this code style is anti-pattern, the code still can be run in environment.

How to explain it?


FYI.

These links maybe not permanent.

Husky
  • 542
  • 5
  • 22
  • 2
    Function declarations within blocks aren't standard afaik, so you shouldn't expect the behavior to be the same across implementations. – elclanrs Jul 27 '16 at 05:40

3 Answers3

2

Javascript engines are not hoisting javascript function the same way, so you can expect different behavior between browser/node.

One exemple of this: http://statichtml.com/2011/spidermonkey-function-hoisting.html

Gatsbill
  • 1,760
  • 1
  • 12
  • 25
1

Ok, So I looked at your code and analyzed it on both native browser and nodeJS. As far as I know, In node the function with same name on second declaration gets overwritten but its not the case in native browser javascript. To look further into the working of the two environments use following code and you will see the difference:

if (1) {
    console.log('In condition 1');
    function foo() { 
        console.log('Inside first declaration');
        return 'a'; 
    }
} else {
    console.log('In condition 2');
    function foo() {
        console.log('Inside second declaration');
        return 'b'; 
    }
}

console.log(foo());
0
if (1) {
    foo();
} else {
foo1();
}
function foo() { return 'a'; }
function foo1() { return 'b'; }
console.log(foo());

Function behavior in a block may be different. Above code works perfectly as expected.

Nikhil.Patel
  • 959
  • 9
  • 17
  • Thanks for your reply. But I want to know why the results are different, instead of getting a better coding style. :) – Husky Jul 27 '16 at 05:52
  • Refer the below link for more explaination 'http://stackoverflow.com/questions/10069204/function-declarations-inside-if-else-statements' – Nikhil.Patel Jul 27 '16 at 05:55