Why a named function declaration isn't hoisted if you put it inside the return statement?

68
January 01, 2020, at 11:10 AM

is putting the function declaration beside the return statement causing the function not to hoist? or putting it inside the return statement turns it into a function expression that's why it isn't hoisted?

// Hoisting doesn't work in here
function outer() {
  console.log(inner); // Isn't hoisted
  return function inner() {
    console.log("hello world");
  };
}

// Works in here
function outer() {
  console.log(inner);
  function inner() {
    console.log("hello world");
  }
  return inner;
}
Answer 1

If you put a function immediately after the return keyword, it's no longer a function declaration; return can only have an expression to the right of it, so it's interpretered as a function expression, and function expressions aren't hoisted (or have their name put into the surrounding scope as a variable).

This isn't something particular to return. Any other keyword that forces the function part to be interpreted as an expression will have the same effect:

function outer() { 
  console.log(typeof inner); // Isn't hoisted 
  if (function inner() { 
    console.log("hello world"); 
  }) { 
  } 
} 
outer();

function outer() { 
  console.log(typeof inner); // Isn't hoisted 
  switch (function inner() { console.log("hello world"); }) { 
   
  } 
} 
outer();

function outer() { 
  console.log(typeof inner); // Isn't hoisted 
  const x = function inner() { 
    console.log("hello world"); 
  }; 
} 
outer();

For a function to be interpreted as a function declaration (and function declarations are the only functions which get hoisted), the function must be a standalone statement, not directly connected to any other statements in the code via operators or keywords.

READ ALSO
how to set the parameter NODE_EXTRA_CA_CERTS in the project instead of the scripts

how to set the parameter NODE_EXTRA_CA_CERTS in the project instead of the scripts

I have an api testing project build with nodejs and Jest which send http requests to multiple domain using the 'request-promise' npm package

146
Angular 4 Universal SSR- ReferenceError: document is not defined

Angular 4 Universal SSR- ReferenceError: document is not defined

I am trying to accomplish Server side rendering for Angular 4 but getting error "ReferenceError: document is not defined" -some people suggested to add dominojs but still getting error after adding domino js in server

154
Unable to call cloudwatch putMetricData in nodejs lambda function

Unable to call cloudwatch putMetricData in nodejs lambda function

I'm trying to use putmetric method to push some logs from my code,Everything is getting executed except this part cwputMetricData and my requirement is the handler should be async

73
i can't load data from mongoDB using Angular 8

i can't load data from mongoDB using Angular 8

I can't load data from MongoDB using Angular 8

88