Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why function aren't hoisted after return statement?

Tags:

javascript

const func = () => {
  someFunction() // error here
  
  return function someFunction() {
    console.log('hello')
  }
}

func()

I've created closure and wanted to check hoisting inside of func function. Each time when you create function declaration it hoists your variable up to the top. Why is someFunction not hoisted?

like image 474
Andrey Radkevich Avatar asked Dec 07 '22 10:12

Andrey Radkevich


2 Answers

When you put a function after return statement, it no longer is a function declaration, but rather a function expression. Unlike declarations, function expressions are not hoisted.

Function expressions in JavaScript are not hoisted, unlike function declarations.

- MDN

like image 174
Nick Parsons Avatar answered Dec 28 '22 07:12

Nick Parsons


You have a (named) function expression in your return statement. This function is not a function statement and because of this, it is not hoisted.

Another reason is, a function expression has no name. That means, you can not access it by the a name outside of the function. The name of a function expression is only available inside of the function with it name (for example for recursions).

like image 24
Nina Scholz Avatar answered Dec 28 '22 06:12

Nina Scholz