FAQ Topic - What is a function statement? (2010-05-24)

F

FAQ server

-----------------------------------------------------------------------
FAQ Topic - What is a function statement?
-----------------------------------------------------------------------

The term function statement has been widely and wrongly used to
describe a ` FunctionDeclaration `. This is misleading because in
ECMAScript, a ` FunctionDeclaration ` cannot appear as a Statement.
To add to this confusion, some implementations, notably Mozillas', provide
a syntax extension called function statement. This is allowed under
section 16 of ECMA-262, Editions 3 and 5.

Example of function statement (nonstandard):

// Nonstandard syntax, found in GMail source code. DO NOT USE.
try {
// FunctionDeclaration not allowed in Block.
function Fze(b,a){return b.unselectable=a}
/*...*/
} catch(e) { _DumpException(e) }

Implementations that have the function statement extension process ` Fze `
as a Statement, in order, while other known implementations evaluate
` Fze ` upon entering the execution context that it appears in.
For consistent behavior across implementations, avoid function statement;
use either ` FunctionExpression ` or ` FunctionDeclaration ` instead.

Example of ` FunctionExpression ` (valid):

var Fze;
try {
Fze = function(b,a){return b.unselectable=a};
/*...*/
} catch(e) { _DumpException(e) }

Example of ` FunctionDeclaration ` (valid):

// Program code
function aa(b,a){return b.unselectable=a}

http://jibbering.com/faq/example/functionStatement.html

https://mail.mozilla.org/pipermail/es-discuss/2008-February/005314.html

http://groups.google.com/group/comp.lang.javascript/msg/aa9a32d0c6ae0342

http://groups.google.com/group/comp.lang.javascript/msg/3987eac87ad27966

http://nanto.asablo.jp/blog/2005/12/10/172622

(Article in Japanese)


The complete comp.lang.javascript FAQ is at
http://jibbering.com/faq/
 
D

Dmitry A. Soshnikov

MDC, unfortunately, doesn't describe Mozilla's function statements very
well, so I did it in NFE article, for anyone interested —
<http://yura.thinkweb2.com/named-function-expressions/#function-statements>

Yep, as addition an appropriate section from my article:
<http://dmitrysoshnikov.com/ecmascript/chapter-5-functions/#feature-of-named-function-expression-nfe>

with all consequences for some SpiderMonkey versions:

<http://dmitrysoshnikov.com/ecmascript/chapter-5-functions/#nfe-and-spidermonkey>

and JScript:

<http://dmitrysoshnikov.com/ecmascript/chapter-5-functions/#nfe-and-jscript>

Dmitry.
 
D

Dmitry A. Soshnikov

New FAQ Topic idea:

| What is a FunctionDeclaration?

?

There should be described the general points of this type of
functions:

<http://dmitrysoshnikov.com/ecmascript/chapter-5-functions/#function-
declaration>

To avoid some technical terms (because this is a FAQ, but not a deep
article), it can be described as:

This is a function which:

- always has a name;
- is created before the code execution;
- available for an execution via its name before and after its
definition in the source code position (in contrast see <link
FunctionExpression />);
- can appear in the source code position directly either at /Program/
level or in the FunctionBody of another function (in any other
position FunctionDeclaration cannot appear, i.e. it is impossible to
define it in the expression or statement position; in contrast see
some implementations extension <link FunctionStatement />).

P.S.: in addition, it is a bit ugly to use BNF non-terminals such as
<FunctionStatement> and other. They are related only with lexical
grammar lexers/parsers, but not with human reading. I prefer a
<Function Expression> instead.

Dmitry.
 
R

Ry Nohryb

-----------------------------------------------------------------------
FAQ Topic - What is a function statement?
-----------------------------------------------------------------------

The term function statement has been widely and wrongly used to
describe a ` FunctionDeclaration `. This is misleading because in
ECMAScript, a ` FunctionDeclaration ` cannot appear as a Statement.

You're misleading, and your screwed-up FAQ too:

12.5: The if Statement: Syntax: if ( Expression ) Statement

javascript: f(); if (0) function f () { alert("Declaration, Smith, DE-
CLA-RA-TION") };

Safari, Chrome, Opera, IE: "Declaration, Smith, DE-CLA-RA-TION"
Mozillas: TypeError: f is not a function.

12.1 Block: Syntax: { StatementList }

javascript: { f(); function f () { alert("Declaration, Smith, DE-CLA-
RA-TION") }; }

Safari, Chrome, Opera, IE: "Declaration, Smith, DE-CLA-RA-TION"
Mozillas: TypeError: f is not a function.

12.6 Iteration Statements: Syntax: do Statement while(Expression);

javascript: f(); do function f () { alert("Declaration, Smith, DE-CLA-
RA-TION") } while (0);

Safari, Chrome, Opera, IE: "Declaration, Smith, DE-CLA-RA-TION"
Mozillas: TypeError: f is not a function.

12.6 Iteration Statements: Syntax: while ( Expression ) Statement

javascript: f(); while (0) function f () { alert("Declaration, Smith,
DE-CLA-RA-TION") };

Safari, Chrome, Opera, IE: "Declaration, Smith, DE-CLA-RA-TION"
Mozillas: TypeError: f is not a function.

12.6 Iteration Statements: Syntax: for (Expression; Expression ;
Expression) Statement

javascript: f(); for (;false;) function f () { alert("Declaration,
Smith, DE-CLA-RA-TION") }

Safari, Chrome, Opera, IE: "Declaration, Smith, DE-CLA-RA-TION"
Mozillas: TypeError: f is not a function.

etc, etc.
To add to this confusion, some implementations, notably Mozillas', provide
a syntax extension called function statement. This is allowed under
section 16 of ECMA-262, Editions 3 and 5.

To your confusion, might be. The whole thing, reworded, could end up
being true. But the way you've got it worded now, it isn't.
 
D

Dmitry A. Soshnikov

You're misleading, and your screwed-up FAQ too:

12.5: The if Statement: Syntax: if ( Expression ) Statement

javascript: f(); if (0) function f () { alert("Declaration, Smith, DE-
CLA-RA-TION") };

Safari, Chrome, Opera, IE: "Declaration, Smith, DE-CLA-RA-TION"
Mozillas: TypeError: f is not a function.

12.1 Block: Syntax: { StatementList }

javascript: { f(); function f () { alert("Declaration, Smith, DE-CLA-
RA-TION") }; }

Safari, Chrome, Opera, IE: "Declaration, Smith, DE-CLA-RA-TION"
Mozillas: TypeError: f is not a function.

12.6 Iteration Statements: Syntax: do Statement while(Expression);

javascript: f(); do function f () { alert("Declaration, Smith, DE-CLA-
RA-TION") } while (0);

Safari, Chrome, Opera, IE: "Declaration, Smith, DE-CLA-RA-TION"
Mozillas: TypeError: f is not a function.

12.6 Iteration Statements: Syntax: while ( Expression ) Statement

javascript: f(); while (0) function f () { alert("Declaration, Smith,
DE-CLA-RA-TION") };

Safari, Chrome, Opera, IE: "Declaration, Smith, DE-CLA-RA-TION"
Mozillas: TypeError: f is not a function.

12.6 Iteration Statements: Syntax: for (Expression; Expression ;
Expression) Statement

javascript: f(); for (;false;) function f () { alert("Declaration,
Smith, DE-CLA-RA-TION") }

Safari, Chrome, Opera, IE: "Declaration, Smith, DE-CLA-RA-TION"
Mozillas: TypeError: f is not a function.

etc, etc.

Well, all excluding Mozilla are wrong. Mozilla is right only because of
section 16 of the ECMA-262-3.

By the way, I have any idea why they didn't standardized Function
Statements in the 5th edition?

That strange phrase from the spec /"ExpressionStatement cannot start
with the *function* keyword because that might make it ambiguous with a
FunctionDeclaration"/ is really strange -- because how then Mozilla
distinguishes FD from FS? Easy I guess, by the context of the source
code position. For what to write it in the spec (including 5th edition),
if it is easy to distinguish? And I think for some it would be
convenient to define functions in the declaration view.

Such dynamically created (on condition at runtime) functions (exactly in
declaration view I mean) there are even in PHP.

Dmitry.
 
R

Richard Cornford

Well, all excluding Mozilla are wrong.

All are right (to the extent that Ry Nohryb observed/demonstrated)
because in every case what they are doing can qualify as an extension
to ECMAScript.
Mozilla is right only because of
section 16 of the ECMA-262-3.

By the way, I have any idea why they didn't standardized Function
Statements in the 5th edition?

There was an attempt to move function declarations into the set of
Statements. When I looked at the proposed drafts at the time it was
clear that the work in doing that had hardly been started and what
they had would never work. But that was quite near their proposed
completion date for the new spec so it was probably easier to go back
to what had been there before than to resolve the issues trying to
make them a type of statement was going to bring up.
That strange phrase from the spec /"ExpressionStatement cannot
start with the *function* keyword because that might make it
ambiguous with a FunctionDeclaration"/ is really strange --
because how then Mozilla distinguishes FD from FS? Easy I
guess, by the context of the source code position. For what
to write it in the spec (including 5th edition), if it is easy
to distinguish?

Have you noticed that section 5.1.1 (3rd Ed.) is entitle "Context-Free
Grammars"? It is quite a change to switch from context-free to context
dependent.
And I think for some it would be convenient to
define functions in the declaration view.
<snip>

How much difference in 'convenience' would there be? You can evaluate
a function expression conditionally and assign the result to a
variable, so whatever the job is it can be done with existing syntax.
So the difference in convenience is that between writing - x =
function(n){ ... }; - and - function x(n){ ... } -, which doesn't seem
that much.

Richard.
 
R

Ry Nohryb

Well, all excluding Mozilla are wrong.

No, no one but Smith is wrong : his statement is obviously false: "in
ECMAScript, a ` FunctionDeclaration ` cannot appear as a Statement" is
FALSE.
Mozilla is right only because of section 16 of the ECMA-262-3.

All of them are fully compliant.
 
D

Dmitry A. Soshnikov

All are right (to the extent that Ry Nohryb observed/demonstrated)
because in every case what they are doing can qualify as an extension
to ECMAScript.

Seems I didn't understand/translate correctly Ry Nohryb's description.
You mean -- it doesn't matter -- whether it is a function declaration
(which is created on entering the context) or a function statement
(which the same as function expression and created by the Function
constructor is created at code execution), i.e. both of them can be
treated as just an allowed extension?
There was an attempt to move function declarations into the set of
Statements. When I looked at the proposed drafts at the time it was
clear that the work in doing that had hardly been started and what
they had would never work. But that was quite near their proposed
completion date for the new spec so it was probably easier to go back
to what had been there before than to resolve the issues trying to
make them a type of statement was going to bring up.

I see, so maybe it was too hard to update their parsers and the "level
of convenience" was recognized as not so high to deal with that.
Have you noticed that section 5.1.1 (3rd Ed.) is entitle "Context-Free
Grammars"? It is quite a change to switch from context-free to context
dependent.

Yes, of course, I understand. So, the Mozilla just extended their parser
for that.
<snip>

How much difference in 'convenience' would there be? You can evaluate
a function expression conditionally and assign the result to a
variable, so whatever the job is it can be done with existing syntax.
So the difference in convenience is that between writing - x =
function(n){ ... }; - and - function x(n){ ... } -, which doesn't seem
that much.

Well, it's another question. I think there is nothing bad to have such
alternative.

From the other hand, today I see (e.g. in some Node.js files) that some
always use function expressions to define a function (even, if it isn't
required) -- yes, making anonymous functions assigning them to
variables. Maybe it is already a habit, maybe just for to be consistent
(because some module functions in Node.js should be exported as FE's
into the special /exports/ object, or to /this/ value as this == exports
there), maybe to avoid the fact that FD available before definition in
the source code position. But it is. So for them of course there's no
convenience/difference in using a function declaration style
conditionally, because they always use function expressions.

I think it is a matter of taste (if all using conditions are the same
and provides the same results). Personally, I don't feel a big need in
function statements (and do no use them of course) but just it was
interesting for me, why if for Mozilla it was easy to implement it, then
why the spec continues to write that it is somehow hard. Yes, a context
free grammar can be the answer.

Dmitry.
 
R

Richard Cornford

Seems I didn't understand/translate correctly Ry Nohryb's
description. You mean -- it doesn't matter -- whether it is
a function declaration (which is created on entering the
context) or a function statement (which the same as function
expression and created by the Function constructor is created
at code execution), i.e. both of them can be treated as just
an allowed extension?

Yes, ECMA syntax doesn't allow for either so if they are there they
must be extensions. Extensions are allowed so neither can be
considered wrong (on the surface, even if IE's treating named function
expressions as 'out of context' function declarations, and so
potentially producing two function objects, is so unhelpfully odd that
it would be better considered a bug than an extension). There has
never been any reason for expecting two different ECMAScript
implementations to have the same extensions, so there is no reason for
expecting the same non-(ECMA)standard syntax to result in the same
behaviour in two different environments. (Of course if an environment
claims to be JavaScript(tm) compatible in addition to being ECMAScript
compatible then it should be reproducing the extensions found in
JavaScript(tm)).

Yes, of course, I understand. So, the Mozilla just extended
their parser for that.

Many of the compiling optimisations that are possible are very context
related so it is very likely that most (of not all) production
javascript compliers are context sensitive in reality, even if the
language's specification does not require that.
Well, it's another question. I think there is nothing bad to
have such alternative.

I can see nothing wrong with having the alternative, and we do have
that alternative. What we don't have is any guarantee of having that
alternative everywhere (which, given we know that the same syntax will
be subject to alternative interpretation in some environments, makes
the alternative non-viable for non-specialised use) .
From the other hand, today I see (e.g. in some Node.js files)
that some always use function expressions to define a function
(even, if it isn't required)

It is a gathering trend, and one I have commented on from time to
time. Generally I don't approve of that trend. I think that if a
function can be a function declaration then it should be (and the
cases when it cannot be one are the special cases), but that probably
is a matter of style/taste.
-- yes, making anonymous functions assigning them to
variables. Maybe it is already a habit, maybe just for to be
consistent (because some module functions in Node.js should
be exported as FE's into the special /exports/ object, or to
/this/ value as this == exports there), maybe to avoid the
fact that FD available before definition in the source code
position. But it is. So for them of course there's no
convenience/difference in using a function declaration style
conditionally, because they always use function expressions.

I think it is a matter of taste (if all using conditions are
the same and provides the same results). Personally, I don't
feel a big need in function statements (and do no use them of
course) but just it was interesting for me, why if for Mozilla
it was easy to implement it, then why the spec continues to
write that it is somehow hard. Yes, a context free grammar can
be the answer.

There was a proposal to do the new (then ES4) spec in ML; to have the
whole ECMAScript language fully defined in the form of ML code. That
could have included a parser and so not be so bound by how ECMAScript
is currently defined. I didn't think that was such a great plan as it
would have rendered the spec even more esoteric than it already is
(and I wasn't buying the argument that those who could not understand
the spec could then learn the language from books, given how very bad
most javascript books are), but it would have been interesting to see
the outcome.

Richard.
 
D

Dmitry A. Soshnikov

Yes, ECMA syntax doesn't allow for either so if they are there they
must be extensions. Extensions are allowed so neither can be
considered wrong

Yes, it seems quite logical.
(on the surface, even if IE's treating named function
expressions as 'out of context' function declarations, and so
potentially producing two function objects, is so unhelpfully odd that
it would be better considered a bug than an extension). There has
never been any reason for expecting two different ECMAScript
implementations to have the same extensions, so there is no reason for
expecting the same non-(ECMA)standard syntax to result in the same
behaviour in two different environments. (Of course if an environment
claims to be JavaScript(tm) compatible in addition to being ECMAScript
compatible then it should be reproducing the extensions found in
JavaScript(tm)).

Yes, that's true.
Many of the compiling optimisations that are possible are very context
related so it is very likely that most (of not all) production
javascript compliers are context sensitive in reality, even if the
language's specification does not require that.

To say precisely we have to analyze the source codes of the
implementation; although, it also seems to me logical if some
implementation makes optimizations based even on parsing stage.

It is a gathering trend, and one I have commented on from time to
time. Generally I don't approve of that trend. I think that if a
function can be a function declaration then it should be (and the
cases when it cannot be one are the special cases), but that probably
is a matter of style/taste.

Yes, moreover, the most general purpose of a function expression to be
used in an expression, e.g. as an functional argument for some
higher-order function (relating e.g to the lambda calculus), and _do not
pollute the outer variable object/environment record_. In contrast a
function declaration from this position -- is just a casual subroutine
for a code reuse and encapsulating/abstracting some actions. But seems,
some once have seen that "coolness" can use FE everywhere. Well, they
are free to do that, that their choice. The only thing I want, that they
understand why do they use it and whether it is really needed to use
exactly a function expression.
There was a proposal to do the new (then ES4) spec in ML; to have the
whole ECMAScript language fully defined in the form of ML code. That
could have included a parser and so not be so bound by how ECMAScript
is currently defined.

Yeah, I've heard something about it. Recent mailings also provides some
spec described in alternative syntax (lambda JS if I remember correctly).
I didn't think that was such a great plan as it
would have rendered the spec even more esoteric than it already is

Depends, we have to see. The idea to describe a spec on the language
itself at least deserves attention. Although, it is a bit odd -- we
don't know yet a language (we're reading a spec), but already see this
language in algorithm descriptions.

In general, yes, an abstract algorithmic language (or even just abstract
algorithms) is enough for the technical spec for implementers.
(and I wasn't buying the argument that those who could not understand
the spec could then learn the language from books, given how very bad
most javascript books are), but it would have been interesting to see
the outcome.

Recently in ML Douglas Crockford was arguing that a spec should be
described that every JS programmer can understand it. That's a noble
idea of course, but seems he forgets that a technical spec -- is a
technical spec (i.e. a requirements specification), but isn't an
interesting literary reading. Although, some (including me) provides the
alternative spec description in more human view (i.e. not only dry
theoretical algorithms, but also "an interesting literary" descriptions
without losing in the accuracy of the spec's info). So don't think that
a technical algorithms will be changed to just a just descriptions.

The most parts of the spec help to understand how does something work
(again -- just an exact algorithm). But at the same time the ECMAScript
provides its own abstraction level, and exactly ECMAScript programmers
are not required to think about _implementations details_. It could be
easier to say them that there is something called as a "variable
hoisting" (a thinking out simplified concept to understand the things),
rather than, "the handling of the execution context code is divided on
two stages: the entering the context and the code execution, and all
data (vars, FD, formal parameters) are created at the first stage --
that's why they are available before the definition in the source code
position".

Yes, it will be interesting to see the outcome, although, we already can
see some implementation on JS -- Narcissus -- there all that algorithms
are described very interesting on JavaScript.

Dmitry.
 
G

Garrett Smith

You're misleading, and your screwed-up FAQ too:

I think I got what that was intended to mean.

12.5: The if Statement: Syntax: if ( Expression ) Statement

Now I'm not sure.
javascript: f(); if (0) function f () { alert("Declaration, Smith, DE-
CLA-RA-TION") };

This is looking like another case of you getting frustrated while trying
to explain something that you think you understand, badly.
Safari, Chrome, Opera, IE: "Declaration, Smith, DE-CLA-RA-TION"
Mozillas: TypeError: f is not a function.

That is probably some sort of evidence supporting your personal beliefs
about the language.
12.1 Block: Syntax: { StatementList }

That is the production for Block.

[...]

[snip more examples]
etc, etc.


To your confusion, might be. The whole thing, reworded, could end up
being true. But the way you've got it worded now, it isn't.
You have communicated well enough that you don't understand what you're
arguing about.

The problem is not a (just) matter of English; yours is barely
comprehensible. No, the problem is that you disrupt discussions with
your misunderstanding and irrelevant quips in a childish way. It is a
deficit to the discussion and a waste of time.

New killfile, entry #1: Jorge Chamorro
 
G

Garrett Smith

No, no one but Smith is wrong : his statement is obviously false: "in
ECMAScript, a ` FunctionDeclaration ` cannot appear as a Statement" is
FALSE.

No, no one but Jorge Chamorro is wrong (and only apparently now that an
actual claim was made).

A Statement cannot begin with "function". Any implementation that allows
for such production is providing a syntax extension.
All of them are fully compliant.

Providing a syntax extension is not a conformance violation.
 
J

John G Harris

No, no one but Smith is wrong : his statement is obviously false: "in
ECMAScript, a ` FunctionDeclaration ` cannot appear as a Statement" is
FALSE.
<snip>

If he changed it slightly to

"in ECMAScript a FunctionDeclaration cannot appear everywhere that a
Statement can appear."

then it would be completely accurate and true.

John
 
G

Garrett Smith

<snip>

If he changed it slightly to

"in ECMAScript a FunctionDeclaration cannot appear everywhere that a
Statement can appear."

then it would be completely accurate and true.

How about:
| in ECMAScript a FunctionDeclaration is not a Statement; it cannot
| appear everywhere that a Statement can.
 
A

Asen Bozhilov

Dmitry said:
By the way, I have any idea why they didn't standardized Function
Statements in the 5th edition?

That strange phrase from the spec /"ExpressionStatement cannot start
with the *function* keyword because that might make it ambiguous with a
FunctionDeclaration"/ is really strange -- because how then Mozilla
distinguishes FD from FS? Easy I guess, by the context of the source
code position. For what to write it in the spec (including 5th edition),
if it is easy to distinguish? And I think for some it would be
convenient to define functions in the declaration view.

FunctionStatement does not provide any syntactical differences with
FD. But provides differences during instantiation stage. Function
Declarations are instated on entering on execution context, but
Function Statements during evaluation of the statement in which they
are defined. That provides a confusion in the readers of the code. For
example:

if (true) {
function F(){
//...
}
}
else {
function F(){
//...
}
}

F();

Which function will be invoked? Yes, you know the answer, but that
example can be extended and code in these statement can be increased.
When you read the code you will be need to see parent statement to
catch that function is actually FS. That break readability of the code
and does not provide any benefits comparing with FunctionExpression
there can be assigned reference on variable. Actually if I modify that
example to use FunctionExpression the readability problem is gone away
and I think maintaining is better.

var F;
if (true) {
F = function () {
//...
}
}
else {
F = function () {
//...
}
}

When I need FunctionStatement behavior I always use
FunctionExpression. That I do for readability and for unexpected
behavior which can be provided by extension on the language. These
extensions can be treat in different way in different
implementations.
 
G

Garrett Smith

Brendan's comments in the es-discuss message linked from the entry
indicate that time was the matter.
var F;
if (true) {
F = function () {
//...
}
}
else {
F = function () {
//...
}
}

[...]

That approach is used for function rewriting. The idea is to create a
function gets the correct function, performing the test of which
function to get in scope of the outer function. I like this pattern,
which Richard has coined the "Russian Doll".

With function rewriting, conditional tests are performed on an as-needed
basis. If that function is never called, the feature tests are not
performed. The practical implication is a function that may or may not
be called. For example, the developer cannot be certain that the user
will click on a button which triggers an event handler that he has coded.

There are variations, but they basically boil down to something that
resembles the following:

myModule.meth = meth ;

function meth (obj, type) {
var meth;
cond = typeof document.createDesktopApplication != "undefined";
if(cond) {
meth = function(obj, type){ /*...*/ };
} else {
meth = function(obj, type){ /*...*/ };
}
(myModule.meth = meth)(obj, type);
}

Caveat: if `meth` nested function makes a `this` reference, it will not
be `myModule` but global object or, in ES5, null.

http://groups.google.com/group/comp...807130df58b?lnk=st&q=&rnum=2#be985807130df58b
 
G

Garrett Smith

MDC, unfortunately, doesn't describe Mozilla's function statements very
well, so I did it in NFE article, for anyone interested —
<http://yura.thinkweb2.com/named-function-expressions/#function-statements>

I've linked the article from the "what is (function{/*...*/})" entry and
from the FAQ notes It's a great article and everybody should read it.
Would it be redundant to link to it again from this entry? The
"Functions" section has no main text. Perhaps the link could go there,
provided something were written as a main entry for that section.
Curiously, older Safari (<=3.0.4) and some versions of Blackberry
browser implement function statements identically to Mozilla's extension.

Interesting. Maybe Safari changed to match IE so they could get badly
authored IE-only sites working.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,705
Latest member
Stefkari24

Latest Threads

Top