1
function sum(a) {

  let currentSum = a;

  function f(b) {
    currentSum += b;
    return f;
   }

  f.toString = function() {
    return currentSum;
  };
  console.log(f);
  return f;
}

alert( sum(1)(2) ); // 3
alert( sum(5)(-1)(2) ); // 6

please help me to understand the difference between - return f and f(). what happen with function code when activate return f? how it work? why console.log(f) return a number? i know f() return result, but return f? i dont understand.

4 Answers4

1

In Javascript functions are first class objects. You can treat a function like any other variable or object, and pass them to functions, assign to other variables, and (as in this case) return them from functions.

A perhaps simpler example to show it might be something like

function foo() {
    console.log("foo called");
}

bar = foo;  // Assign the function foo to the variable bar
            // Note that this doesn't actually call foo

bar();  // Now we call the foo function

My own example here is quite useless and only to show the principle. For a more useful example it's common for functions to return references to other functions, like in the example inside the question.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

It happens to be that when you try to console.log any value it invokes "toString" method.

In your instance you override toString method instead of default implementation it returns a number

Sonahit
  • 1
  • 1
  • 2
0

The function without the () is a pointer to the function. I use it with setTimeout all the time.

function doSomething() {
    console.log('something');
}

setTimeout(doSomething, 5000);
tinymothbrain
  • 412
  • 2
  • 6
0

Each time you invoke sum function, you are always returning reference of function f. So sum(1) will return the reference of f, while sum(1).toString() will return the 1 sum(1)(2) will return reference of f, while sum(1)(2).toString() will return 3

It is not recursion because you returning just the reference. So until you invoke it, the function is not called

Sandeep Nagaraj
  • 118
  • 1
  • 11