Randomblue
Randomblue

Reputation: 116343

Function names ending with ()

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:

  1. Execute the argument foo. This assigns myVariable the returned value of foo.
  2. Consider foo() as the name of the function defined at first. This assigns myVariable the empty function.

Is this even legal code? If so, what are the rules?

Upvotes: 2

Views: 223

Answers (5)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039110

Is this even legal code?

No:

var foo() = function () { }; 

should be:

var foo = function () { }; 

If so, what are the rules?

In this case the foo argument will have precedence because it is defined in an inner scope than the foo function. 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 123 as seen in this live demo:

var foo = function () { alert('we are in the foo function'); };
var bar = function(foo) { var myVariable = foo(); alert(myVariable); };
bar(function() { return 123; });

Upvotes: 5

IanNorton
IanNorton

Reputation: 7282

Do you really mean "Can I pass functions as references?" If so, then the answer is yes:

var foo = function() { return 2; }
var bar = function(fn){ return fn(); }

var two = bar(foo);

Upvotes: 0

Alexander Gessler
Alexander Gessler

Reputation: 46637

Identifiers may not contain any parentheses, so the first statement is illegal. The second, however, is fine, myVariable = foo() executes the foo parameter and assigns the return value.

Upvotes: 0

Gazler
Gazler

Reputation: 84180

In javascript, brackets mean execute. So your code will fail as it will be looking for a function foo on the first line.

Upvotes: 1

Marcelo Cantos
Marcelo Cantos

Reputation: 185962

The () isn't considered part of the name. You'll probably get a syntax error. You can find some naming rules here.

Upvotes: 2

Related Questions