So suppose I have something like this
var x = 1;
if (function f(){}) {
x += typeof f;
}
x;
This outputs "1undefined". I thought it should have output "1function", because function f(){} should have been hoisted above the if. This is clearly not the case - why? I thought function declarations and bodies were always hoisted to the top of the scope?
Function expressions in JavaScript are not hoisted. Therefore, you cannot use function expressions before defining them. This is all there is to be kept in mind for creating functions from a hoisting point of view.
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. Inevitably, this means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.
Function definition hoisting only occurs for function declarations, not function expressions. Function expressions are defined with a function as a variable. The definitions look like var b = function() . This kind of function declarations through expressions makes the function NOT Hoisted.
All functions and variables are hoisted. The best way to understand function hoisting is to first look into how variable hoisting works, the principles are similar and will give an understanding for functions. The following code will show the intended output of something with the declaration written afterwards.
Function declarations are hoisted. Function expressions are not.
This creates a named function expression:
if(function f(){})
It doesn't do anything except check to see if the function expression is truthy. (Function expressions are always truthy.)
Regarding named function expressions, see https://kangax.github.io/nfe/#named-expr:
An important detail to remember is that this name is only available in the scope of a newly-defined function
This code is outside the scope of the new function expression, and therefore f
is undefined:
x += typeof f;
Within a named function expression, you can refer to its name without a problem:
(function f() {
alert(typeof f); //function
})();
alert(typeof f); //undefined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With