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 } }
just_a_newbie
  • 375
  • 1
  • 3
  • 8

4 Answers4

6

Call the returned value of the function:

foo(1)(2);
Matthew Mcveigh
  • 5,635
  • 20
  • 22
6

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
Community
  • 1
  • 1
Bergi
  • 572,313
  • 128
  • 898
  • 1,281
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...

Hogan
  • 65,989
  • 10
  • 76
  • 113
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.

Mehran Hatami
  • 12,355
  • 6
  • 27
  • 35