0

I've just started learning about function. and here is what gives me difficulty.

const Func = () => {
  return () => {
    console.log('hello');
  };
};

const innerFunc = Func();

innerFunc(); // 1.

Func(); //2.

I don't understand why 'hello' doesn't show up on console trying with 2.

Aren't both innerFunc and Func names of function?

I don't know the difference between them.

Sorry for my bad English.

pilchard
  • 12,414
  • 5
  • 11
  • 23
정재상
  • 17
  • 4
  • 7
    `Func()` returns another function `() => {console.log('hello')}`, so when you call `Func()` and assign the result to innerFunc, innerFunc then holds a reference to this second function. (`innerFunc = () => {console.log('hello')}`) see: [Functions that return a function](https://stackoverflow.com/questions/7629891/functions-that-return-a-function) – pilchard Oct 31 '21 at 00:57
  • 2
    You are returning a function from a function, so you have to use `Func()();` – DecPK Oct 31 '21 at 01:00
  • 1
    Please put some effort into formulating a descriptive title – Dexygen Oct 31 '21 at 01:20

3 Answers3

1

Func() returns a function which will not be executed until you run the result with () like you are doing with 1..
By doing const innerFunc = Func();, you are assigning the function returned from Func into innerFunc. So to call it, you need to run it like this: innerFunc().

pazitos10
  • 1,641
  • 16
  • 25
1

Your function 'Func' returns another function from inside, so when you call Func(), then it will return another function which you named as 'innerFunc' and calling innerFunc will return the output as hello.

When you try with Just 'Func()', it will just return another function which you returned inside Func.

0

Starting to learn about functions, just look at

const Func = () => {
    console.log('hello');
};

Func(); // logs hello to the console

What you have here is a function inside of function, which is more complicated and not necessarily beginner friendly.

MikeBarberry
  • 37
  • 2
  • 7