473,396 Members | 2,106 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Function definition inside 'if' statement

Hello,

I debugged some html file and found this:

------------------------------------------------------------
<script language="JavaScript">

if ( some_statement ) {

function MyFunction ( some_argument ) {

some_function_statements;

}

}

</script>
------------------------------------------------------------

Is it allowed to define a function INSIDE some 'if' statement?

Thanks

Henk
Oct 19 '05 #1
8 9593
I believe it is, but this is a subtle area, where different Javascript
engines treat it differently.

In JScript the function will be created, even if the "if" statement
does not apply. I.e. when running a function, it looks for all the
declared sub functions, and creates them.

In Firefox, the function may only be created when the "if" statement
applies.

Oct 19 '05 #2

Henk van Winkoop wrote:
if ( some_statement ) {

function MyFunction ( some_argument ) {

some_function_statements;

}

}
Is it allowed to define a function INSIDE some 'if' statement?


Looks like pretty poor programming to me. Why not have a single
function, with variable parameters inside the "if" loop?

Nigel

Oct 19 '05 #3
On 19/10/2005 10:24, Henk van Winkoop wrote:

[snip]
<script language="JavaScript">
The language attribute has long been deprecated in favour of the
required type attribute:

<script type="text/javascript">
if ( some_statement ) {

function MyFunction ( some_argument ) {

some_function_statements;

}

}
[snip]
Is it allowed to define a function INSIDE some 'if' statement?


Not as a function declaration. However, a function expression can be
used to conditionally create a function object.

There was a recent thread on this topic.

Subject: <variable>=function(){...}
Date: 2005/10/13 20:17 GMT
Message ID: di**********@SonOfMaze.dpo.uab.edu

<URL:http://groups.google.co.uk/group/comp.lang.javascript/browse_thread/thread/e8865df4f3a89f02/22e5fab87e8d2175>

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Oct 19 '05 #4
Michael Winter wrote:-
Not as a function declaration.


This works fine for me in JScript (whether "a" is undefined or not),
although admittedly I have not checked the formal grammar in the ECMA
standard, or tested in Firefox..

function f1(a)
{
if (a){
function f2(){}
}

alert(f2);
}

f1();

Oct 19 '05 #5
On 19/10/2005 11:23, Baconbutty wrote:

[Placing function declarations within block statements]
This works fine for me in JScript [...]
That depends on what you define as 'working'. With a conforming
implementation, a syntax error exception would be thrown. That certainly
doesn't happen in most browsers (as I wrote in the other thread I
mentioned).
although admittedly I have not checked the formal grammar in the ECMA
standard,
It's illegal. I misremembered the precise details at the time of the
other thread (thanks again, David), but a function declaration is only
permitted within the SourceElement production. This is available at
'global' scope (within the Program production) or in the body of a
function (FunctionBody). So,

function myFunction() {}

and

function myOuterFunction() {
function myInnerFunction() {
}
}

are both legal, but nothing else is.

Function expressions enter the grammar in the MemberExpression
production, so they may appear in expressions and expression statements.
However, expression statements may not begin with either the 'function'
or '{' tokens (this is what I forgot), so

if(...) {
function() {
}
}

cannot be considered a legal function expression.
or tested in Firefox..


This is where things get interesting. Consider:

if('function' == typeof myFunction) {alert('before');}
if(true) {
function myFunction() {}
}
if('function' == typeof myFunction) {alert('after');}

In IE, both dialogs boxes are shown, so one can only assume that the
'function' token is used to create a function declaration, therefore the
resulting function object is parsed before execution, and available
before the definition is encountered.

In Fx, only the second dialog box is shown, indicating that not only is
the function conditional (a function expression), but that the
identifier - which should only be available to the function expression,
itself - is leaked into the global object, as well.

This can be confirmed by changing the if statement condition to false,
and witnessing the same behaviour in IE, but nothing in Fx.

The leaking behaviour, mentioned above, is equally odd. In IE, it always
appears to leak the identifier when presented with code like:

var global = function local() {};

However, Fx doesn't, even though it did with the previous case.

With all of this conflicting behaviour, the only sensible course of
action is to avoid doing any of this (which is why I'm not going to test
in other browsers).

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Oct 19 '05 #6

Michael Winter wrote:
That depends on what you define as 'working'. With a conforming
implementation, a syntax error exception would be thrown. That certainly
doesn't happen in most browsers (as I wrote in the other thread I
mentioned).
Fair point. Loose language.
It's illegal. I misremembered the precise details at the time of the
other thread (thanks again, David), but a function declaration is only
permitted within the SourceElement production.
I understand precisely.
However, expression statements may not begin with either the 'function'
or '{' tokens (this is what I forgot),
Presumably so as not to create ambiguity with a Block production or a
FunctionDeclaration production.
In IE, both dialogs boxes are shown, so one can only assume that the
'function' token is used to create a function declaration, therefore the
resulting function object is parsed before execution, and available
before the definition is encountered.

In Fx, only the second dialog box is shown, indicating that not only is
the function conditional (a function expression), but that the
identifier - which should only be available to the function expression,
itself - is leaked into the global object, as well.

This can be confirmed by changing the if statement condition to false,
and witnessing the same behaviour in IE, but nothing in Fx.

The leaking behaviour, mentioned above, is equally odd. In IE, it always
appears to leak the identifier when presented with code like:

var global = function local() {};

However, Fx doesn't, even though it did with the previous case.
I understand.

IE's parser seems to treat anything in the form "function Identifier()"
as a FunctionDeclaration, in whatever grammar context.

Firefox seems to treat a FunctionDeclarations like a Statement.
With all of this conflicting behaviour, the only sensible course of
action is to avoid doing any of this (which is why I'm not going to test
in other browsers).


And presumably it would be a rare and unusual situation where you would
want to conditionally declare a function instead of using a legal
function expression for the purpose.

Oct 19 '05 #7
On 19/10/2005 12:34, Michael Winter wrote:

[snip]
I misremembered the precise details at the time of the other thread
(thanks again, David),

^^^^^
Gaahh! My sincere apologies, Duncan. :(

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Oct 19 '05 #8
On 19/10/2005 13:05, Baconbutty wrote:

[snip]
And presumably it would be a rare and unusual situation where you would
want to conditionally declare a function instead of using a legal
function expression for the purpose.


Absolutely. If conditional creation of a function was the goal, then the
condition would have to be reached and evaluated before the result could
be obtained. As such, it wouldn't matter how that function object was
defined: other parts of the program couldn't use it until after the
condition, so one may as well use a legal production.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Oct 19 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: Gaurav Veda | last post by:
Hi ! I am a poor mortal who has become terrified of Python. It seems to have thrown all the OO concepts out of the window. Penniless, I ask a basic question : What is the difference between a...
4
by: gf | last post by:
<script> function testme(testvar) { if (testvar=='1') { alert('testvar=1'); document.open(); document.write('This is just some text<br /><br />"); document.write('<a...
7
by: Newbie_sw2003 | last post by:
Where should I use them? I am giving you my understandings. Please correct me if I am wrong: MACRO: e.g.:#define ref-name 99 The code is substituted by the MACRO ref-name. So no overhead....
9
by: Netocrat | last post by:
Any comments on the correctness of the statements 1, 2a, 2b, 3 and 4 in the code below? If they are correct, then the definition of an object as well as that of an lvalue is broken in C99 by the...
4
by: Michael | last post by:
Hi, I'm having difficulty finding any previous discussion on this -- I keep finding people either having problems calling os.exec(lepev), or with using python's exec statement. Neither of...
4
by: Paulo Matos | last post by:
Hi all, I'm trying to work out a parser for function declarations but it turns out that it is harder than I initially thought. I'm looking at 3rd Ed of Stroustrup, page 808. I'm trying to parse...
11
by: =?iso-8859-1?q?Erik_Wikstr=F6m?= | last post by:
struct foo { int i; }; int bar(foo& f) { return f.i++; } int main() { bar(foo());
9
by: CryptiqueGuy | last post by:
Consider the variadic function with the following prototype: int foo(int num,...); Here 'num' specifies the number of arguments, and assume that all the arguments that should be passed to this...
49
by: Davy | last post by:
Hi all, I am writing a function, which return the pointer of the int. But it seems to be wrong. Any suggestion? int * get_p_t(int t) { return &t; } int main()
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.