Function declarations

In terms of scoping, function declarations behave similarly to variable declarations (that is, var). They will be scoped to their closest function, module, or global environment, and will be hoisted to the top of their respective execution context.

Unlike variable declarations, however, a function declaration will cause the actual assignment of the Function to its identifier to be hoisted as well, meaning that the Function is effectively available before it is declared:

myFunction(); // => "This works!"
function myFunction() { return 'This works!' }

This behavior is quite obscure and as such is inadvisable unless it is very obvious where the definition for myFunction comes from upon invocation. A programmer will typically expect a definition for a function to exist above the place where it is called (or imported as a dependency at some prior point in time), so it can be confusing.

There is further complexity if we consider the possibility of a function declaration residing within a block that is conditionally activated (warning: don't do this!):

giveMeTheBestNumber; // => (Varies depending on implementation!)
if (something) {
function giveMeTheBestNumber() { return 76; }
} else {
function giveMeTheBestNumber() { return 42; }
}

Unfortunately, previous versions of ECMAScript did not prescribe the behavior of function declarations within blocks. This led to various browser implementations choosing their own unique way of handling such situations. Over time, implementations have begun to align. The ECMAScript 2015 specification sensibly forbids either of the giveMeTheBestNumber functions from having their values hoisted. The declaration itself can, however, still be hoisted, meaning that giveMeTheBestNumber would be undefined on lines prior to its declarations (similar to var), as mentioned. This is, at the time of writing, the prevalent behavior of most (but not all) implementations.

Because of the obscurity and the remaining inconsistencies across implementations, it is strongly suggested that you don't use function declarations within blocks. And ideally, it's best not to rely on their hoisting behavior (by referencing function declarations) unless you're confident that doing so would not be misunderstood by those who must read your code.

For more information on how functions produced by function declarations differ from other ways of creating functions (for example, function expressions or arrow functions), please revisit the Functions section in Chapter 6Primitive and Built-In Types.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.174.174