Access function arguments with forEach - Javascript Function

Javascript examples for Function:Function Call

Description

Access function arguments with forEach

Demo Code


function sum() {/*from   w w w .  ja  v  a  2s  .  c o  m*/
  let result = 0;
  for (let i = 0; i < arguments.length; i++) {
    result += arguments[i];
  }
  return result;
}

console.log(sum(1, 2, 3, 4) === 10);
console.log(sum(1, 2, 3, 4, 5) === 15);

function sum2(...args) {
  let result = 0;
  args.forEach( (el) => {result += el;} );
  return result;
}

console.log(sum2(1, 2, 3, 4) === 10);
console.log(sum2(1, 2, 3, 4, 5) === 15);

Related Tutorials