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

RESOLVED INVALID

Status

()

RESOLVED INVALID
11 years ago
8 years ago

People

(Reporter: djrichard, Unassigned)

Tracking

1.9.0 Branch
x86
Windows Vista
Points:
---

Firefox Tracking Flags

(Not tracked)

Details

(Reporter)

Description

11 years ago
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.
(Reporter)

Updated

11 years ago
Version: unspecified → 3.0 Branch

Updated

11 years ago
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
Last Resolved: 11 years ago
Resolution: --- → INVALID
Duplicate of this bug: 523234
You need to log in before you can comment on or make changes to this bug.