Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a function hoisted if it is defined within an if condition?

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?

like image 461
praks5432 Avatar asked Jul 27 '15 21:07

praks5432


People also ask

Which function are not hoisted?

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.

What does it mean for a function to be hoisted?

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.

Which type of functions are hoisted?

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.

Are all functions 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.


1 Answers

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
like image 165
Rick Hitchcock Avatar answered Dec 07 '22 08:12

Rick Hitchcock