Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested functions Javascript

In a Javascript function, are you required to define nested functions as function expressions or are function declarations allowed in a function body? For example, would something like this be compliant?

function a() {
    function b() {
        function c() {
            window.alert(3);
        }
        window.alert(2);
    }
    window.alert(1);
}

Or would you have to do something like this?

function a() {
    var a = function () {
        var c = function () {
            window.alert(3);
        }
        window.alert(2);
    }
    window.alert(1);
}

ECMA-262 says that:

Several widely used implementations of ECMAScript are known to support the use of FunctionDeclaration as a Statement. However there are significant and irreconcilable variations among the implementations in the semantics applied to such FunctionDeclarations. Because of these irreconcilable differences, the use of a FunctionDeclaration as a Statement results in code that is not reliably portable among implementations. It is recommended that ECMAScript implementations either disallow this usage of FunctionDeclaration or issue a warning when such a usage is encountered. Future editions of ECMAScript may define alternative portable means for declaring functions in a Statement context.

Does this mean that a function declaration in a function body is technically incorrect, or have I got this completely wrong? I've heard people refer to the body as a block, which according to the standard, is one or more statements, but I'm not sure.

like image 422
Qantas 94 Heavy Avatar asked Feb 15 '13 07:02

Qantas 94 Heavy


1 Answers

FunctionDeclaration's are certainly allowed in function body, and there are no bugs I'm aware of.

It's all pretty clear once you look at ES5 production rules

FunctionBody
  SourceElements (opt)

SourceElements
  SourceElement
  SourceElements SourceElement

SourceElement
  Statement
  FunctionDeclaration

In other words, function body includes source elements, and source element is either a Statement or a FunctionDeclaration. Hence FunctionDeclaration can be part of a function body.

The clause you mentioned about "... implementations of ECMAScript ... known to support the use of FunctionDeclaration as a Statement" refers to using FunctionDeclaration as a Statement, but not directly in function body. It's referring to cases like:

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

That is a non-standardized behavior. Check out more on these function statements.

like image 150
kangax Avatar answered Nov 04 '22 11:11

kangax