0

Some languages do not allow you to write more than one function definition with the same name in the same scope. Others allow such duplication (especially scripting and interpreted languages) and the latter definition 'wins'. Consider this Python example:

def foo():
  print("Hello, I'm first foo")

foo()

def foo():
  print("Hello, I'm second foo")

foo()

Output:

Hello, I'm first foo
Hello, I'm second foo

Similar code in Lua and Ruby behaves the same way. But the output of similar Javascript code is different and puzzles me:

Hello, I'm second foo
Hello, I'm second foo

I know how Python works: the source code is compiled and then executed from top to bottom; those 'def' statements are executables, not just statements; after the first definition is executed, the name 'foo' is bound to the first definition and the call foo() executes that function. After executing the second definition, the name 'foo' is rebound to the second definition and its previous value is lost; the second foo() call executes that new function body. Although compilation and execution are separate phases, it behaves roughly as if the interpreter is reading and interpreting the source code line by line. I think both Lua and Ruby follow more or less the same path.

But I wonder, how does Javascript work? When the first foo() call is executed, the second definition is already in place, so the execution is not line-by-line. That's pretty unexpected to me, considering Javascript's origins as a true interpreter. So how exactly is the code analized and interpreted? Links to reference material are welcome; I couldn't find the answer by looking at the ES6 (2015) standard but surely I didn't look in the right place.

0 Answers0