Recursive example

In notebook:
FrontEndMasters Functional light
Created at:
2016-09-24
Updated:
2016-09-24
Tags:
Functional Programming JavaScript
non-recursive sum of three numbers
  function sumIter() {
  var sum = 0;
  for (var i = 0; i < arguments.length; i++) {
    sum = sum + arguments[i]
  }
  return sum;
}

sumIter(3,4,5);   // 12
recursive:
  function sumRecur () {
  var args = [].slice.call(arguments);
  if (args.length <= 2) {
    return args[0] + args[1];
  }
  return (
    args[0] + sumRecur.apply(null,args.sice(1))
  );
}

sumRecur(3,4,5);    // 12
(in ES6 this can be express more pretty)
  function sumRecur(...args) {
  if (args.length <= 2) {
    return args[0] + args[1];
  }
  return (
    args[0] + sumRecur(...args.slice(1))
  );
}

sumRecur(3,4,5);    // 12
the magic is in ​...​ rest operator. Works in arguments as well (to call another function).Note: arguments are what you pass into a function, parameters are what the function receives.