Function declarations

Function declarations are a type of hoisted declaration. A hoisted declaration is one that will, at runtime, be effectively hoisted up the top of its execution context, meaning that it will be immediately accessible to preceding lines of code (seemingly before it's declared):

hoistedDeclaration(); // => Does not throw an error...

function hoistedDeclaration() {}

This, of course, is not possible with a function expression that's been assigned to a variable:

regularFunctionExpression();
// => Uncaught ReferenceError:
// => Cannot access 'regularFunctionExpression' before initialization

const regularFunctionExpression = function() {};

The hoisted behavior of function declarations can create unexpected results, so it is typically considered an anti-pattern to rely on the hoist. In general, it's fine to use function declarations, as long as they're used in a way that respects the assumptions that programmers will intuitively make. Hoisting, as a practice, is not very intuitive to most people, and so it's usually best to avoid it.

For more information on scopes and how hoisting occurs in the case of function declarations, please take a look at Chapter 9Parts of Syntax and Scope, and go to the Scopes and Declarations section.
..................Content has been hidden....................

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