Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which JS function-declaration syntax is correct according to the standard?

  var foo = function(){ return 1; };
  if (true) {
    function foo(){ return 2; }
  }
  foo(); // 1 in Chrome // 2 in FF
  //I just want to be sure, is FF 4 not "standard" in this case?

Edit:

what if we have this:

  var foo = function(){ return 1; };
  if (true) function foo(){ return 2; }      
  foo(); // is 1 standard or is 2 standard?
like image 753
Pacerier Avatar asked Apr 22 '11 17:04

Pacerier


2 Answers

The original poster's code isn't permitted by the ECMAScript standard. (ECMAScript the official name for the JavaScript language specification, for legal reasons.) It is, however, a common extension to the language—one which is, unfortunately, implemented differently in different browsers.

In standard JavaScript, function definitions may only occur in top level code, or at the top level of a function's body. You can't have conditionals, loops, or even curly braces between the enclosing function's body and the the function definition.

For example, this is permitted:

  function f() {
    function g() {
      ...
    }
  }

but this is not:

  function f() {
    {
      function g() {
        ...
      }
    }
  }

What complicates the picture is that most browsers do accept this latter code, but each assigns its own idiosyncratic interpretation to it. Firefox treats it like:

  function f() {
    {
      var g = function g() {
        ...
      }
    }
  }

The ECMAScript committee is considering choosing a specific interpretation for these "function statements" (as opposed to function definitions). They haven't made a decision yet. Mozilla is discussing its preferred solution here.

like image 123
Jim Blandy Avatar answered Oct 06 '22 17:10

Jim Blandy


The code in the question is not actually allowed at all by current ECMAScript syntax (as of ECMAScript 5). You can do var foo = function() {} inside a block, but you can only do function foo() {} at the toplevel in functions or scripts.

Currently browsers support the code in the question in incompatible ways because they're all implementing extensions to the core language and they implement different extensions. A fully conforming ECMAScript 5 implementation would actually end up with a SyntaxError when compiling this script.

There are proposals to add the ability to do this sort of thing to ECMAScript, but they're not quite finalized yet.

like image 37
Boris Zbarsky Avatar answered Oct 06 '22 15:10

Boris Zbarsky