1

How to call this function in Javascript? As it takes n as its outer function's parameter and it also needs another parameter i in its function inside, but how to call it?

function foo(n) { 
  return function (i) { 
           return n += i } }
1
  • It does return a function. Call that. Commented Feb 23, 2014 at 18:51

4 Answers 4

5

Call the returned value of the function:

foo(1)(2);
Sign up to request clarification or add additional context in comments.

Comments

5

It a classic closure example: it does return a function which has access to the n variable.

var counter = foo(0);
counter(1); // 1
counter(2); // 3
counter(5); // 8

1 Comment

It "keeps" the n variable that was created in the foo() call
4

This is a function that returns a function. Often you would want a reference to that function, Like this

 foofn = foo(7);
 result = foofn(7);

You could also just call the function right away

 result = (foo(7))(7);

What the function does? Well that wasn't really your question...

Comments

2

This is the way we usually use JavaScript closures, first function creates a scope to keep the n variable safe to be used in the inner function:

var n = 11;
var myfunc = foo(n);

now you can call your myfunc function, with a simple i argument, whereas it uses n without you needing to pass it directly to your function:

myfunc(10);

so if you want to just call it, once it is created, you can do: foo(11)(10);

But in these cases we don't usually call them like this, they are usually supposed to be used as a callback or something like it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.