Marian Roshchupkin
Marian Roshchupkin

Reputation: 13

why are nested functions executed when I only invoke it through a variable?

why do I have to write a variable, assign a function to it and only after that it works fine. Why?

I have been searching it on Google and found almost the same question here Why can't I invoke a function directly?. But the problem is that his code is complex and all people's explanations about his code are based on his one whereas I'm beginner so I don't entirely understand his code, thus explantions too

My code

function foo() {
  let a = 10;
  let b = 20;

  function bar() {
    return a + b;
  }

  return bar;
}

foo();

But if assign the function to a variable, it works.

let x = foo();
x();

Upvotes: 0

Views: 36

Answers (1)

Felix Kling
Felix Kling

Reputation: 816770

This has nothing to do with variables. A variable is just a container for a value. You can easily omit the variable assignment without changing the behavior of your program.

So lets work backwards and remove x from your second example:

// `x` is the same as `foo()`
// `x()` therefor becomes
foo()()

And now you should see the difference:

foo()   // first example
// vs
foo()() // second example

foo returns a function. You have to call that function. And you already know that functions are called with (). So foo()() calls foo, and then calls the return value of foo.

Here is a simplified example:

function foo() {
  console.log('inside foo');
  function bar() {
    console.log('inside bar');
  }
  return bar;
}

console.log('foo()');
foo();
console.log('foo()()');
foo()();

Upvotes: 4

Related Questions