Skip to content

Instantly share code, notes, and snippets.

@ugultopu
Last active December 26, 2020 23:52
Show Gist options
  • Save ugultopu/816f1636360a994e7e1314863713b6ff to your computer and use it in GitHub Desktop.
Save ugultopu/816f1636360a994e7e1314863713b6ff to your computer and use it in GitHub Desktop.
Semantics of defining a function within a block in JavaScript

UPDATE

Apparently, "function statements" (that is, "block-level function declarations") have been standardized in ES6 (ES2015). This question contains more information about their behavior. However, before ES6 (that is, on ES5 and before), they are not standard. Read the following for more information.

Original Text

In JavaScript, we have function declarations:

function someFunction(/* Some parameters */) {
  // Some code
}

Function expressions:

let someVar = function someFunction(/* Some parameters */) {
  // Some code
}

or

let someVar = function(/* Some parameters */) {
  // Some code
}

Given those, then what is the following:

function someOtherFunction(/* Some parameters */) {
  // Some code
  if (/* Some condition */) {
    function someFunction(/* Some other parameters */) {
      // Some code
    }
  }
}

What is someFunction here? Well it cannot be a function expression, because it is not on the right hand side being assigned to something. Then it must be a function declaration right? Well, wrong. A function declaration, by definition, cannot appear within a block. Since someFunction appears inside of an if block, it is neither a function expression, nor a function declaration. It is something called a "function statement". A function statement is a function declaration that is located in a block, instead of being located either in the global scope, or directly in the body of another function, without being nested in a block.

The implementation of the function statements are not always consistent across different JavaScript implementations. Hence, it is recommended not to use function statements, and only use function declarations or function expressions. That is, when your program logic requires defining a function within a block, use a function expression instead of using a function statement. Or, if possible, change the implementation so that it uses function declarations (that is, the functions are defined either in the global scope, or directly in other functions, without being nested in any blocks).

Sources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment