-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?

5
  • 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? Commented Apr 29, 2019 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. Commented Apr 29, 2019 at 14:42
  • @briosheje Well. You could, it just wouldn't work the way the OP wants it to. Commented Apr 29, 2019 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. Commented Apr 29, 2019 at 14:44
  • 1
    try: var f = new getFunc(); Commented Feb 29, 2020 at 22:45

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

3 Comments

"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?"
Yes, but I think the OP is asking why it is this way, not a way to eliminate the intermediate variable.
Yes @DaveNewton this is exactly what I needed. Thank you
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.