How does JavaScript deal with functions with names ending with ()? Consider for example the following piece of code:
var foo() = function () { }; // The empty function
var bar = function(foo) { var myVariable = foo(); };
It seems like there are two possible interpretations for what foo(); means:
- Execute the argument
foo. This assignsmyVariablethe returned value offoo. - Consider
foo()as the name of the function defined at first. This assignsmyVariablethe empty function.
Is this even legal code? If so, what are the rules?
No:
should be:
In this case the
fooargument will have precedence because it is defined in an inner scope than thefoofunction. So it’s really a matter of scope: where is the variable defined. The interpreter first starts by looking in the innermost scope of the code, then in the outer, … until it reaches the global scope (the window object).So for example the result of the following code will be
123as seen in this live demo: