-1

I was taking a small test online and there was this code:

function getFunc() {
    var a = 7;
    return function(b) {
        alert(a+b);
    }
}
var f = getFunc();
f(5);

I would like to know why I can't call getFunct(5) directly for example.

I don't understand the last two lines.

Why do I need to assign the function to a variable. What happens when doing f(5)?

How does JS interpret that the 5 is a variable for the inner function and not the outer?

Emma
  • 27,428
  • 11
  • 44
  • 69
user3808307
  • 2,270
  • 9
  • 45
  • 99
  • Because that's not the definition of `getFunc`. `getFunc` *returns* a function you call with a parameter. Look at the signature of `getFunc`: is there a parameter? – Dave Newton Apr 29 '19 at 14:42
  • `getFunc` **returns** a `function`. So, `f` is just the inner function where the contextual `a` is 7. You shouln't directly call it, because the call signature of `getFunc` just doesn't accept any argument, so calling it with any argument will do nothing. – briosheje Apr 29 '19 at 14:42
  • @briosheje Well. You *could*, it just wouldn't work the way the OP wants it to. – Dave Newton Apr 29 '19 at 14:43
  • @DaveNewton You're right, you technically _could_ indeed, but that would do nothing. However, that's right, you actually **can** do that, but it just won't do anything. – briosheje Apr 29 '19 at 14:44
  • 1
    try: **var f = new getFunc();** – Zibri Feb 29 '20 at 22:45

2 Answers2

7

You could call the inner function immediately after calling the first one, because the first call returns a function and the second call gives the result.

function getFunc() {
    var a = 7;
    return function(b) {
        console.log(a + b);
    }
}

getFunc()(5);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • _"I don't understand the last two lines. Why do I need to assign the function to a variable. What happens when doing f(5)? How does JS interpret that the 5 is a variable for the inner function and not the outer?"_ – Andreas Apr 29 '19 at 14:42
  • 2
    Yes, but I think the OP is asking *why* it is this way, not a way to eliminate the intermediate variable. – Dave Newton Apr 29 '19 at 14:43
  • Yes @DaveNewton this is exactly what I needed. Thank you – user3808307 Apr 29 '19 at 14:58
3

By assigning getFunc() to the variable f you actually assigned the return value i.e. inner function to f since that's what getFunc is returning. The braces () make a difference here.

However had it been f = getFunc i.e. without the braces, that would imply f is an alias for getFunc and you'd have to do f()(5) in that case.