Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function declarations in Native browser and Node.js, get differnt results [duplicate]

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.

  • Node.js environment Link: https://repl.it/CgWh

  • Native Browser environment Link: https://repl.it/CgWj

These links maybe not permanent.

like image 773
Husky Avatar asked Oct 19 '22 05:10

Husky


1 Answers

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

like image 194
Gatsbill Avatar answered Oct 22 '22 11:10

Gatsbill