0

For example, in test.js this is allowed (and extremely pointless):

1 + 2;
(function () {});

When executing with node:

$ node test.js
$

The form function () {} (without parentheses) is allowed in other contexts, for example as an argument to another function.

Why is not the following allowed in the top level of a JavaScript file?

function () {};
3
  • 2
    Why do you need this? A name-less function without any handles to it is just a noop! Commented Jun 3, 2012 at 12:15
  • possible duplicate of Why need I wrap anonymous function in parenthesis before calling it in Javascript? Commented Jun 3, 2012 at 13:57
  • @EmilVikström I certainly don't need it. I'm merely curious as to why it works that way. Commented Jun 3, 2012 at 16:31

1 Answer 1

4

A statement that starts with function is a function statement.
Function statements must be named. (since they create a declaration in that scope)

Sign up to request clarification or add additional context in comments.

8 Comments

The precise term would be function declaration afaik.
@FelixKling: Not according to Firefox: SyntaxError: function statement requires a name
Maybe in JavaScript, but according to ECMAScript: ecma-international.org/ecma-262/5.1/#sec-13
Mozilla Firefox uses FunctionStatement as an extension of a FunctionDecleration (but this is afaik. non-standard). A great explanation can be found here: javascriptweblog.wordpress.com/2010/07/06/…
@SLaks—ECMAScript has only FunctionDeclaration and FunctionExpression, FunctionStatement is a Mozilla JavaScript thing (as Saebekassebil said).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.