O
O
olya_0972018-02-03 01:47:57
JavaScript
olya_097, 2018-02-03 01:47:57

Question on js, return. What does it do?

Hello everyone, I understand that the return returns a value, but can you tell me more about this situation, please,
why do we return f 2 times? And also: is this for a closure?
can you please explain in a nutshell, thanks

function sum(a) {

  var currentSum = a;

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

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

  return f;
}

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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vantsymbalenko, 2018-02-03
@vantsymbalenko

as already answered above, return is made in order to call the function an infinite number of times.
that is, the first time we call a function sum(), it returns a function to us f, which in turn can be called or output the result if it is no longer used using an artificially added method f.toString(). If the function fis called, then when the execution reaches it, currentSum += b;it will not find it in its lexical environment currentSumand through the search above, that is, in the function sum,there, it will find this value and use it. After that, it will return itself so that the user can use the function f again.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question