Closed Bug 444853 Opened 16 years ago Closed 16 years ago

JavaScript function declared in if() block is not defined until if() block executes

Categories

(Core :: JavaScript Engine, defect)

1.9.0 Branch
x86
Windows Vista
defect
Not set
normal

Tracking

()

RESOLVED INVALID

People

(Reporter: djrichard, Unassigned)

Details

User-Agent:       Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9) Gecko/2008052906 Firefox/3.0
Build Identifier: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9) Gecko/2008052906 Firefox/3.0

A JavaScript function defined inside of an if() block is not defined until that if() block executes.  

The following works:
function afterIfBlock()
{
  if (1 == 1)
  {
    function doStuff(input)
    {
      alert(input);
    }
  }

  doStuff('called after if block');
}

The following results in the error 'doStuff is not defined':
function beforeIfBlock()
{
  doStuff('called before if block');
  if (1 == 1)
  {
    function doStuff(input)
    {
      alert(input);
    }
  }
}



Reproducible: Always

Steps to Reproduce:
1. Declare a JavaScript function inside of an if() block.
2. Attempt to reference said function before the if() block would be evaluated.

Actual Results:  
Received a JavaScript error: "ReferenceError: doStuff is not defined".

Expected Results:  
According to section 10.1.3 of ECMA-262, all function declarations in an execution context's code must be processed on entering the execution context.  As if() blocks do not form their own execution context, any function declarations declared inside of if() blocks should be processed (and therefore defined) upon entering the execution context containing the if() block.


Both sample functions work in IE 7, Opera 9.51, and Safari for Windows 3.1.2.  beforeIfBlock() fails in Firefox 2/3.
Version: unspecified → 3.0 Branch
Assignee: nobody → general
Component: General → JavaScript Engine
Product: Firefox → Core
QA Contact: general → general
Version: 3.0 Branch → 1.9.0 Branch
You're misreading ECMA-262 Edition 3. Note that the grammar (not the semantics including section 10) does not produce a function definition nested in a block. It's a syntactic extension about which browsers disagree.

See also bug 417730 and others like it.

/be
Status: UNCONFIRMED → RESOLVED
Closed: 16 years ago
Resolution: --- → INVALID
You need to log in before you can comment on or make changes to this bug.