-1

Just wondering if there is anything different that happens under the hood? At first I thought that x would hold a copy of the sayHello function body but when stepping through the process in the browser's debugger the sayHello function is executed inside of the returnSomeFunction instead. So this got me wondering, is there a way to assign a function call to a variable (in this case x) where the return value is a function definition rather than holding a reference of the function that is inside of returnSomeFunction?

function returnSomeFunction() {
  return function() {
    console.log("Hello There!")
  }
}

function returnSomeFunction() {
  function sayHello() {
    console.log("Hello There!")
  }
  return sayHello;
}

const x = returnSomeFunction();
x();
  • There is no difference. They both return a function reference at the end. – VLAZ Nov 05 '20 at 22:39
  • 1
    Well, one function *has* a [name](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name).. – user2864740 Nov 05 '20 at 22:39
  • 3
    If the first version has a name, there would be literally no difference. Right now there is only *basically* no difference, since the discrepancy is only with the presence of name, as opposed to what is being returned. – VLAZ Nov 05 '20 at 22:43
  • Does this answer your question? [Creating functions dynamically in JS](https://stackoverflow.com/questions/20129236/creating-functions-dynamically-in-js) – pilchard Nov 05 '20 at 22:48
  • @pilchard using the `Function` constructor still returns a reference to a function. What OP is asking for is not really possible. – VLAZ Nov 05 '20 at 22:50

1 Answers1

0

There is no difference between them. Both of them do same job. Only difference which has no effect, is that the second one has a name and first one not. It is better to use second one, to have more clear and pretty code.

Hadi Ahmadi
  • 469
  • 1
  • 3
  • 10
  • You can always have a named function expression `return function myFunction () {}`, so you don't *have* to always use function declarations to have names. – VLAZ Nov 06 '20 at 05:59