Closed Bug 705618 Opened 13 years ago Closed 13 years ago

Javascript function declaration inside an if statement doesn't work as supposed

Categories

(Core :: JavaScript Engine, defect)

8 Branch
x86
Windows XP
defect
Not set
normal

Tracking

()

RESOLVED DUPLICATE of bug 585536

People

(Reporter: piotrek, Unassigned)

Details

Calling a function before it was declared works as supposed:

>>> (function () { foo(); function foo(){ console.log('bar'); } })()
bar


But when the call and declaration are put inside an if statement, script breaks:

>>> (function () { if (true) { foo(); function foo(){ console.log('bar'); } } })()
ReferenceError: foo is not defined

The example above works on WebKit and Internet Explorer.



Though when the function is called after the declaration, it works fine:

>>> (function () { if (true) { function foo(){ console.log('bar'); } foo(); } })()
bar
> Calling a function before it was declared works as supposed:

Yes, per spec function declarations at global and function scope get hoisted just like var.

> But when the call and declaration are put inside an if statement, script breaks:

Per spec, this should throw a parse error while parsing the script: function statements inside if blocks are not allowed in JavaScript.  In practice, various browsers added extensions supporting them, but they handle them very differently as you discovered.  For example, if different branches of the if define the function _differently_ a call after the if will do different things at least in Gecko and IE (and IE's behavior is totally messed up in that case).

You can read more about the whole mess at http://stackoverflow.com/questions/5758042/which-js-function-declaration-syntax-is-correct-according-to-the-standard if you want.

So as far as I can tell this is invalid, pending the spec actually defining behavior here.
Yeah, this is a classic issue.
Status: UNCONFIRMED → RESOLVED
Closed: 13 years ago
Resolution: --- → INVALID
I think Harmony is expected to clean up this part of the spec, although there isn't any information yet at http://wiki.ecmascript.org/doku.php?id=harmony:block_functions.
Resolution: INVALID → DUPLICATE
You need to log in before you can comment on or make changes to this bug.